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 "PPCMachineFunctionInfo.h" 17 #include "PPCPerfectShuffle.h" 18 #include "PPCTargetMachine.h" 19 #include "PPCTargetObjectFile.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/StringSwitch.h" 22 #include "llvm/ADT/Triple.h" 23 #include "llvm/CodeGen/CallingConvLower.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/SelectionDAG.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/IR/CallingConv.h" 31 #include "llvm/IR/Constants.h" 32 #include "llvm/IR/DerivedTypes.h" 33 #include "llvm/IR/Function.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/MathExtras.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/Target/TargetOptions.h" 40 using namespace llvm; 41 42 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 43 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 44 45 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 46 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 47 48 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 49 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 50 51 // FIXME: Remove this once the bug has been fixed! 52 extern cl::opt<bool> ANDIGlueBug; 53 54 static TargetLoweringObjectFile *createTLOF(const Triple &TT) { 55 // If it isn't a Mach-O file then it's going to be a linux ELF 56 // object file. 57 if (TT.isOSDarwin()) 58 return new TargetLoweringObjectFileMachO(); 59 60 return new PPC64LinuxTargetObjectFile(); 61 } 62 63 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM) 64 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))), 65 Subtarget(*TM.getSubtargetImpl()) { 66 setPow2DivIsCheap(); 67 68 // Use _setjmp/_longjmp instead of setjmp/longjmp. 69 setUseUnderscoreSetJmp(true); 70 setUseUnderscoreLongJmp(true); 71 72 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 73 // arguments are at least 4/8 bytes aligned. 74 bool isPPC64 = Subtarget.isPPC64(); 75 setMinStackArgumentAlignment(isPPC64 ? 8:4); 76 77 // Set up the register classes. 78 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 79 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 80 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 81 82 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD 83 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 84 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand); 85 86 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 87 88 // PowerPC has pre-inc load and store's. 89 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 90 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 91 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 92 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 93 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 94 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 95 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 96 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 97 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 98 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 99 100 if (Subtarget.useCRBits()) { 101 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 102 103 if (isPPC64 || Subtarget.hasFPCVT()) { 104 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 105 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 106 isPPC64 ? MVT::i64 : MVT::i32); 107 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 108 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 109 isPPC64 ? MVT::i64 : MVT::i32); 110 } else { 111 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 112 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 113 } 114 115 // PowerPC does not support direct load / store of condition registers 116 setOperationAction(ISD::LOAD, MVT::i1, Custom); 117 setOperationAction(ISD::STORE, MVT::i1, Custom); 118 119 // FIXME: Remove this once the ANDI glue bug is fixed: 120 if (ANDIGlueBug) 121 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 122 123 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 124 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote); 125 setTruncStoreAction(MVT::i64, MVT::i1, Expand); 126 setTruncStoreAction(MVT::i32, MVT::i1, Expand); 127 setTruncStoreAction(MVT::i16, MVT::i1, Expand); 128 setTruncStoreAction(MVT::i8, MVT::i1, Expand); 129 130 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 131 } 132 133 // This is used in the ppcf128->int sequence. Note it has different semantics 134 // from FP_ROUND: that rounds to nearest, this rounds to zero. 135 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); 136 137 // We do not currently implement these libm ops for PowerPC. 138 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 139 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 140 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 141 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 142 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 143 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 144 145 // PowerPC has no SREM/UREM instructions 146 setOperationAction(ISD::SREM, MVT::i32, Expand); 147 setOperationAction(ISD::UREM, MVT::i32, Expand); 148 setOperationAction(ISD::SREM, MVT::i64, Expand); 149 setOperationAction(ISD::UREM, MVT::i64, Expand); 150 151 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 152 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 153 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 154 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 155 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 157 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 158 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 159 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 160 161 // We don't support sin/cos/sqrt/fmod/pow 162 setOperationAction(ISD::FSIN , MVT::f64, Expand); 163 setOperationAction(ISD::FCOS , MVT::f64, Expand); 164 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 165 setOperationAction(ISD::FREM , MVT::f64, Expand); 166 setOperationAction(ISD::FPOW , MVT::f64, Expand); 167 setOperationAction(ISD::FMA , MVT::f64, Legal); 168 setOperationAction(ISD::FSIN , MVT::f32, Expand); 169 setOperationAction(ISD::FCOS , MVT::f32, Expand); 170 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 171 setOperationAction(ISD::FREM , MVT::f32, Expand); 172 setOperationAction(ISD::FPOW , MVT::f32, Expand); 173 setOperationAction(ISD::FMA , MVT::f32, Legal); 174 175 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 176 177 // If we're enabling GP optimizations, use hardware square root 178 if (!Subtarget.hasFSQRT() && 179 !(TM.Options.UnsafeFPMath && 180 Subtarget.hasFRSQRTE() && Subtarget.hasFRE())) 181 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 182 183 if (!Subtarget.hasFSQRT() && 184 !(TM.Options.UnsafeFPMath && 185 Subtarget.hasFRSQRTES() && Subtarget.hasFRES())) 186 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 187 188 if (Subtarget.hasFCPSGN()) { 189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 190 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 191 } else { 192 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 193 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 194 } 195 196 if (Subtarget.hasFPRND()) { 197 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 198 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 199 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 200 setOperationAction(ISD::FROUND, MVT::f64, Legal); 201 202 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 203 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 204 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 205 setOperationAction(ISD::FROUND, MVT::f32, Legal); 206 } 207 208 // PowerPC does not have BSWAP, CTPOP or CTTZ 209 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 210 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand); 212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand); 213 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 214 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand); 216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand); 217 218 if (Subtarget.hasPOPCNTD()) { 219 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 220 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 221 } else { 222 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 223 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 224 } 225 226 // PowerPC does not have ROTR 227 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 228 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 229 230 if (!Subtarget.useCRBits()) { 231 // PowerPC does not have Select 232 setOperationAction(ISD::SELECT, MVT::i32, Expand); 233 setOperationAction(ISD::SELECT, MVT::i64, Expand); 234 setOperationAction(ISD::SELECT, MVT::f32, Expand); 235 setOperationAction(ISD::SELECT, MVT::f64, Expand); 236 } 237 238 // PowerPC wants to turn select_cc of FP into fsel when possible. 239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 241 242 // PowerPC wants to optimize integer setcc a bit 243 if (!Subtarget.useCRBits()) 244 setOperationAction(ISD::SETCC, MVT::i32, Custom); 245 246 // PowerPC does not have BRCOND which requires SetCC 247 if (!Subtarget.useCRBits()) 248 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 249 250 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 251 252 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 254 255 // PowerPC does not have [U|S]INT_TO_FP 256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 257 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 258 259 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 260 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 261 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 262 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 263 264 // We cannot sextinreg(i1). Expand to shifts. 265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 266 267 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 268 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 269 // support continuation, user-level threading, and etc.. As a result, no 270 // other SjLj exception interfaces are implemented and please don't build 271 // your own exception handling based on them. 272 // LLVM/Clang supports zero-cost DWARF exception handling. 273 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 274 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 275 276 // We want to legalize GlobalAddress and ConstantPool nodes into the 277 // appropriate instructions to materialize the address. 278 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 279 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 280 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 281 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 282 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 286 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 287 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 288 289 // TRAP is legal. 290 setOperationAction(ISD::TRAP, MVT::Other, Legal); 291 292 // TRAMPOLINE is custom lowered. 293 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 294 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 295 296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 297 setOperationAction(ISD::VASTART , MVT::Other, Custom); 298 299 if (Subtarget.isSVR4ABI()) { 300 if (isPPC64) { 301 // VAARG always uses double-word chunks, so promote anything smaller. 302 setOperationAction(ISD::VAARG, MVT::i1, Promote); 303 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 304 setOperationAction(ISD::VAARG, MVT::i8, Promote); 305 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 306 setOperationAction(ISD::VAARG, MVT::i16, Promote); 307 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 308 setOperationAction(ISD::VAARG, MVT::i32, Promote); 309 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 310 setOperationAction(ISD::VAARG, MVT::Other, Expand); 311 } else { 312 // VAARG is custom lowered with the 32-bit SVR4 ABI. 313 setOperationAction(ISD::VAARG, MVT::Other, Custom); 314 setOperationAction(ISD::VAARG, MVT::i64, Custom); 315 } 316 } else 317 setOperationAction(ISD::VAARG, MVT::Other, Expand); 318 319 if (Subtarget.isSVR4ABI() && !isPPC64) 320 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 321 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 322 else 323 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 324 325 // Use the default implementation. 326 setOperationAction(ISD::VAEND , MVT::Other, Expand); 327 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 328 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 331 332 // We want to custom lower some of our intrinsics. 333 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 334 335 // To handle counter-based loop conditions. 336 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 337 338 // Comparisons that require checking two conditions. 339 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 340 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 341 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 342 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 343 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 344 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 345 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 346 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 347 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 348 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 349 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 350 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 351 352 if (Subtarget.has64BitSupport()) { 353 // They also have instructions for converting between i64 and fp. 354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 355 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 358 // This is just the low 32 bits of a (signed) fp->i64 conversion. 359 // We cannot do this with Promote because i64 is not a legal type. 360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 361 362 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 364 } else { 365 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 366 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 367 } 368 369 // With the instructions enabled under FPCVT, we can do everything. 370 if (Subtarget.hasFPCVT()) { 371 if (Subtarget.has64BitSupport()) { 372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 373 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 376 } 377 378 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 379 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 382 } 383 384 if (Subtarget.use64BitRegs()) { 385 // 64-bit PowerPC implementations can support i64 types directly 386 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 387 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 388 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 389 // 64-bit PowerPC wants to expand i128 shifts itself. 390 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 391 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 392 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 393 } else { 394 // 32-bit PowerPC wants to expand i64 shifts itself. 395 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 396 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 397 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 398 } 399 400 if (Subtarget.hasAltivec()) { 401 // First set operation action for all vector types to expand. Then we 402 // will selectively turn on ones that can be effectively codegen'd. 403 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 404 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) { 405 MVT::SimpleValueType VT = (MVT::SimpleValueType)i; 406 407 // add/sub are legal for all supported vector VT's. 408 setOperationAction(ISD::ADD , VT, Legal); 409 setOperationAction(ISD::SUB , VT, Legal); 410 411 // We promote all shuffles to v16i8. 412 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 413 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 414 415 // We promote all non-typed operations to v4i32. 416 setOperationAction(ISD::AND , VT, Promote); 417 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 418 setOperationAction(ISD::OR , VT, Promote); 419 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 420 setOperationAction(ISD::XOR , VT, Promote); 421 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 422 setOperationAction(ISD::LOAD , VT, Promote); 423 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 424 setOperationAction(ISD::SELECT, VT, Promote); 425 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 426 setOperationAction(ISD::STORE, VT, Promote); 427 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 428 429 // No other operations are legal. 430 setOperationAction(ISD::MUL , VT, Expand); 431 setOperationAction(ISD::SDIV, VT, Expand); 432 setOperationAction(ISD::SREM, VT, Expand); 433 setOperationAction(ISD::UDIV, VT, Expand); 434 setOperationAction(ISD::UREM, VT, Expand); 435 setOperationAction(ISD::FDIV, VT, Expand); 436 setOperationAction(ISD::FREM, VT, Expand); 437 setOperationAction(ISD::FNEG, VT, Expand); 438 setOperationAction(ISD::FSQRT, VT, Expand); 439 setOperationAction(ISD::FLOG, VT, Expand); 440 setOperationAction(ISD::FLOG10, VT, Expand); 441 setOperationAction(ISD::FLOG2, VT, Expand); 442 setOperationAction(ISD::FEXP, VT, Expand); 443 setOperationAction(ISD::FEXP2, VT, Expand); 444 setOperationAction(ISD::FSIN, VT, Expand); 445 setOperationAction(ISD::FCOS, VT, Expand); 446 setOperationAction(ISD::FABS, VT, Expand); 447 setOperationAction(ISD::FPOWI, VT, Expand); 448 setOperationAction(ISD::FFLOOR, VT, Expand); 449 setOperationAction(ISD::FCEIL, VT, Expand); 450 setOperationAction(ISD::FTRUNC, VT, Expand); 451 setOperationAction(ISD::FRINT, VT, Expand); 452 setOperationAction(ISD::FNEARBYINT, VT, Expand); 453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 454 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 455 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 456 setOperationAction(ISD::MULHU, VT, Expand); 457 setOperationAction(ISD::MULHS, VT, Expand); 458 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 459 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 460 setOperationAction(ISD::UDIVREM, VT, Expand); 461 setOperationAction(ISD::SDIVREM, VT, Expand); 462 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 463 setOperationAction(ISD::FPOW, VT, Expand); 464 setOperationAction(ISD::BSWAP, VT, Expand); 465 setOperationAction(ISD::CTPOP, VT, Expand); 466 setOperationAction(ISD::CTLZ, VT, Expand); 467 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand); 468 setOperationAction(ISD::CTTZ, VT, Expand); 469 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand); 470 setOperationAction(ISD::VSELECT, VT, Expand); 471 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 472 473 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 474 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) { 475 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j; 476 setTruncStoreAction(VT, InnerVT, Expand); 477 } 478 setLoadExtAction(ISD::SEXTLOAD, VT, Expand); 479 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand); 480 setLoadExtAction(ISD::EXTLOAD, VT, Expand); 481 } 482 483 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 484 // with merges, splats, etc. 485 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 486 487 setOperationAction(ISD::AND , MVT::v4i32, Legal); 488 setOperationAction(ISD::OR , MVT::v4i32, Legal); 489 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 490 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 491 setOperationAction(ISD::SELECT, MVT::v4i32, 492 Subtarget.useCRBits() ? Legal : Expand); 493 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 494 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 495 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 496 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 497 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 498 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 499 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 500 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 501 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 502 503 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 504 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 505 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 506 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 507 508 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 509 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 510 511 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 512 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 513 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 514 } 515 516 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 517 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 518 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 519 520 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 521 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 522 523 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 524 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 525 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 526 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 527 528 // Altivec does not contain unordered floating-point compare instructions 529 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 530 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 531 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 532 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 533 534 if (Subtarget.hasVSX()) { 535 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 536 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 537 538 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 539 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 540 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 541 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 542 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 543 544 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 545 546 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 547 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 548 549 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 550 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 551 552 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 553 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 554 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 555 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 556 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 557 558 // Share the Altivec comparison restrictions. 559 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 560 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 561 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 562 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 563 564 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 565 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 566 567 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 568 569 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 570 571 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 572 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 573 574 // VSX v2i64 only supports non-arithmetic operations. 575 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 576 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 577 578 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 579 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 580 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 581 582 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 583 584 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 585 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 586 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 587 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 588 589 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 590 591 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 592 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 593 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 594 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 595 596 // Vector operation legalization checks the result type of 597 // SIGN_EXTEND_INREG, overall legalization checks the inner type. 598 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 599 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 600 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 601 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 602 603 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 604 } 605 } 606 607 if (Subtarget.has64BitSupport()) { 608 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 609 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 610 } 611 612 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand); 613 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand); 614 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 615 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 616 617 setBooleanContents(ZeroOrOneBooleanContent); 618 // Altivec instructions set fields to all zeros or all ones. 619 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 620 621 if (!isPPC64) { 622 // These libcalls are not available in 32-bit. 623 setLibcallName(RTLIB::SHL_I128, nullptr); 624 setLibcallName(RTLIB::SRL_I128, nullptr); 625 setLibcallName(RTLIB::SRA_I128, nullptr); 626 } 627 628 if (isPPC64) { 629 setStackPointerRegisterToSaveRestore(PPC::X1); 630 setExceptionPointerRegister(PPC::X3); 631 setExceptionSelectorRegister(PPC::X4); 632 } else { 633 setStackPointerRegisterToSaveRestore(PPC::R1); 634 setExceptionPointerRegister(PPC::R3); 635 setExceptionSelectorRegister(PPC::R4); 636 } 637 638 // We have target-specific dag combine patterns for the following nodes: 639 setTargetDAGCombine(ISD::SINT_TO_FP); 640 setTargetDAGCombine(ISD::LOAD); 641 setTargetDAGCombine(ISD::STORE); 642 setTargetDAGCombine(ISD::BR_CC); 643 if (Subtarget.useCRBits()) 644 setTargetDAGCombine(ISD::BRCOND); 645 setTargetDAGCombine(ISD::BSWAP); 646 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 647 648 setTargetDAGCombine(ISD::SIGN_EXTEND); 649 setTargetDAGCombine(ISD::ZERO_EXTEND); 650 setTargetDAGCombine(ISD::ANY_EXTEND); 651 652 if (Subtarget.useCRBits()) { 653 setTargetDAGCombine(ISD::TRUNCATE); 654 setTargetDAGCombine(ISD::SETCC); 655 setTargetDAGCombine(ISD::SELECT_CC); 656 } 657 658 // Use reciprocal estimates. 659 if (TM.Options.UnsafeFPMath) { 660 setTargetDAGCombine(ISD::FDIV); 661 setTargetDAGCombine(ISD::FSQRT); 662 } 663 664 // Darwin long double math library functions have $LDBL128 appended. 665 if (Subtarget.isDarwin()) { 666 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 667 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 668 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 669 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 670 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 671 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 672 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 673 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 674 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 675 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 676 } 677 678 // With 32 condition bits, we don't need to sink (and duplicate) compares 679 // aggressively in CodeGenPrep. 680 if (Subtarget.useCRBits()) 681 setHasMultipleConditionRegisters(); 682 683 setMinFunctionAlignment(2); 684 if (Subtarget.isDarwin()) 685 setPrefFunctionAlignment(4); 686 687 if (isPPC64 && Subtarget.isJITCodeModel()) 688 // Temporary workaround for the inability of PPC64 JIT to handle jump 689 // tables. 690 setSupportJumpTables(false); 691 692 setInsertFencesForAtomic(true); 693 694 if (Subtarget.enableMachineScheduler()) 695 setSchedulingPreference(Sched::Source); 696 else 697 setSchedulingPreference(Sched::Hybrid); 698 699 computeRegisterProperties(); 700 701 // The Freescale cores does better with aggressive inlining of memcpy and 702 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores). 703 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 704 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 705 MaxStoresPerMemset = 32; 706 MaxStoresPerMemsetOptSize = 16; 707 MaxStoresPerMemcpy = 32; 708 MaxStoresPerMemcpyOptSize = 8; 709 MaxStoresPerMemmove = 32; 710 MaxStoresPerMemmoveOptSize = 8; 711 712 setPrefFunctionAlignment(4); 713 } 714 } 715 716 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 717 /// the desired ByVal argument alignment. 718 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 719 unsigned MaxMaxAlign) { 720 if (MaxAlign == MaxMaxAlign) 721 return; 722 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 723 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 724 MaxAlign = 32; 725 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 726 MaxAlign = 16; 727 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 728 unsigned EltAlign = 0; 729 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 730 if (EltAlign > MaxAlign) 731 MaxAlign = EltAlign; 732 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 733 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 734 unsigned EltAlign = 0; 735 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign); 736 if (EltAlign > MaxAlign) 737 MaxAlign = EltAlign; 738 if (MaxAlign == MaxMaxAlign) 739 break; 740 } 741 } 742 } 743 744 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 745 /// function arguments in the caller parameter area. 746 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const { 747 // Darwin passes everything on 4 byte boundary. 748 if (Subtarget.isDarwin()) 749 return 4; 750 751 // 16byte and wider vectors are passed on 16byte boundary. 752 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 753 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 754 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 755 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 756 return Align; 757 } 758 759 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 760 switch (Opcode) { 761 default: return nullptr; 762 case PPCISD::FSEL: return "PPCISD::FSEL"; 763 case PPCISD::FCFID: return "PPCISD::FCFID"; 764 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 765 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 766 case PPCISD::FRE: return "PPCISD::FRE"; 767 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 768 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 769 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 770 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 771 case PPCISD::VPERM: return "PPCISD::VPERM"; 772 case PPCISD::Hi: return "PPCISD::Hi"; 773 case PPCISD::Lo: return "PPCISD::Lo"; 774 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 775 case PPCISD::LOAD: return "PPCISD::LOAD"; 776 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC"; 777 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 778 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 779 case PPCISD::SRL: return "PPCISD::SRL"; 780 case PPCISD::SRA: return "PPCISD::SRA"; 781 case PPCISD::SHL: return "PPCISD::SHL"; 782 case PPCISD::CALL: return "PPCISD::CALL"; 783 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 784 case PPCISD::CALL_TLS: return "PPCISD::CALL_TLS"; 785 case PPCISD::CALL_NOP_TLS: return "PPCISD::CALL_NOP_TLS"; 786 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 787 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 788 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 789 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 790 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 791 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 792 case PPCISD::VCMP: return "PPCISD::VCMP"; 793 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 794 case PPCISD::LBRX: return "PPCISD::LBRX"; 795 case PPCISD::STBRX: return "PPCISD::STBRX"; 796 case PPCISD::LARX: return "PPCISD::LARX"; 797 case PPCISD::STCX: return "PPCISD::STCX"; 798 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 799 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 800 case PPCISD::BDZ: return "PPCISD::BDZ"; 801 case PPCISD::MFFS: return "PPCISD::MFFS"; 802 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 803 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 804 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 805 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 806 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA"; 807 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L"; 808 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L"; 809 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 810 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 811 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 812 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 813 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 814 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 815 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 816 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 817 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 818 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 819 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 820 case PPCISD::SC: return "PPCISD::SC"; 821 } 822 } 823 824 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const { 825 if (!VT.isVector()) 826 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 827 return VT.changeVectorElementTypeToInteger(); 828 } 829 830 //===----------------------------------------------------------------------===// 831 // Node matching predicates, for use by the tblgen matching code. 832 //===----------------------------------------------------------------------===// 833 834 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 835 static bool isFloatingPointZero(SDValue Op) { 836 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 837 return CFP->getValueAPF().isZero(); 838 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 839 // Maybe this has already been legalized into the constant pool? 840 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 841 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 842 return CFP->getValueAPF().isZero(); 843 } 844 return false; 845 } 846 847 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 848 /// true if Op is undef or if it matches the specified value. 849 static bool isConstantOrUndef(int Op, int Val) { 850 return Op < 0 || Op == Val; 851 } 852 853 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 854 /// VPKUHUM instruction. 855 /// The ShuffleKind distinguishes between big-endian operations with 856 /// two different inputs (0), either-endian operations with two identical 857 /// inputs (1), and little-endian operantion with two different inputs (2). 858 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 859 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 860 SelectionDAG &DAG) { 861 if (ShuffleKind == 0) { 862 if (DAG.getTarget().getDataLayout()->isLittleEndian()) 863 return false; 864 for (unsigned i = 0; i != 16; ++i) 865 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 866 return false; 867 } else if (ShuffleKind == 2) { 868 if (!DAG.getTarget().getDataLayout()->isLittleEndian()) 869 return false; 870 for (unsigned i = 0; i != 16; ++i) 871 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 872 return false; 873 } else if (ShuffleKind == 1) { 874 unsigned j = DAG.getTarget().getDataLayout()->isLittleEndian() ? 0 : 1; 875 for (unsigned i = 0; i != 8; ++i) 876 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 877 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 878 return false; 879 } 880 return true; 881 } 882 883 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 884 /// VPKUWUM instruction. 885 /// The ShuffleKind distinguishes between big-endian operations with 886 /// two different inputs (0), either-endian operations with two identical 887 /// inputs (1), and little-endian operantion with two different inputs (2). 888 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 889 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 890 SelectionDAG &DAG) { 891 if (ShuffleKind == 0) { 892 if (DAG.getTarget().getDataLayout()->isLittleEndian()) 893 return false; 894 for (unsigned i = 0; i != 16; i += 2) 895 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 896 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 897 return false; 898 } else if (ShuffleKind == 2) { 899 if (!DAG.getTarget().getDataLayout()->isLittleEndian()) 900 return false; 901 for (unsigned i = 0; i != 16; i += 2) 902 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 903 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 904 return false; 905 } else if (ShuffleKind == 1) { 906 unsigned j = DAG.getTarget().getDataLayout()->isLittleEndian() ? 0 : 2; 907 for (unsigned i = 0; i != 8; i += 2) 908 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 909 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 910 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 911 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 912 return false; 913 } 914 return true; 915 } 916 917 /// isVMerge - Common function, used to match vmrg* shuffles. 918 /// 919 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 920 unsigned LHSStart, unsigned RHSStart) { 921 if (N->getValueType(0) != MVT::v16i8) 922 return false; 923 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 924 "Unsupported merge size!"); 925 926 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 927 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 928 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 929 LHSStart+j+i*UnitSize) || 930 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 931 RHSStart+j+i*UnitSize)) 932 return false; 933 } 934 return true; 935 } 936 937 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 938 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 939 /// The ShuffleKind distinguishes between big-endian merges with two 940 /// different inputs (0), either-endian merges with two identical inputs (1), 941 /// and little-endian merges with two different inputs (2). For the latter, 942 /// the input operands are swapped (see PPCInstrAltivec.td). 943 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 944 unsigned ShuffleKind, SelectionDAG &DAG) { 945 if (DAG.getTarget().getDataLayout()->isLittleEndian()) { 946 if (ShuffleKind == 1) // unary 947 return isVMerge(N, UnitSize, 0, 0); 948 else if (ShuffleKind == 2) // swapped 949 return isVMerge(N, UnitSize, 0, 16); 950 else 951 return false; 952 } else { 953 if (ShuffleKind == 1) // unary 954 return isVMerge(N, UnitSize, 8, 8); 955 else if (ShuffleKind == 0) // normal 956 return isVMerge(N, UnitSize, 8, 24); 957 else 958 return false; 959 } 960 } 961 962 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 963 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 964 /// The ShuffleKind distinguishes between big-endian merges with two 965 /// different inputs (0), either-endian merges with two identical inputs (1), 966 /// and little-endian merges with two different inputs (2). For the latter, 967 /// the input operands are swapped (see PPCInstrAltivec.td). 968 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 969 unsigned ShuffleKind, SelectionDAG &DAG) { 970 if (DAG.getTarget().getDataLayout()->isLittleEndian()) { 971 if (ShuffleKind == 1) // unary 972 return isVMerge(N, UnitSize, 8, 8); 973 else if (ShuffleKind == 2) // swapped 974 return isVMerge(N, UnitSize, 8, 24); 975 else 976 return false; 977 } else { 978 if (ShuffleKind == 1) // unary 979 return isVMerge(N, UnitSize, 0, 0); 980 else if (ShuffleKind == 0) // normal 981 return isVMerge(N, UnitSize, 0, 16); 982 else 983 return false; 984 } 985 } 986 987 988 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 989 /// amount, otherwise return -1. 990 /// The ShuffleKind distinguishes between big-endian operations with two 991 /// different inputs (0), either-endian operations with two identical inputs 992 /// (1), and little-endian operations with two different inputs (2). For the 993 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 994 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 995 SelectionDAG &DAG) { 996 if (N->getValueType(0) != MVT::v16i8) 997 return -1; 998 999 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1000 1001 // Find the first non-undef value in the shuffle mask. 1002 unsigned i; 1003 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1004 /*search*/; 1005 1006 if (i == 16) return -1; // all undef. 1007 1008 // Otherwise, check to see if the rest of the elements are consecutively 1009 // numbered from this value. 1010 unsigned ShiftAmt = SVOp->getMaskElt(i); 1011 if (ShiftAmt < i) return -1; 1012 1013 ShiftAmt -= i; 1014 bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian(); 1015 1016 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1017 // Check the rest of the elements to see if they are consecutive. 1018 for (++i; i != 16; ++i) 1019 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1020 return -1; 1021 } else if (ShuffleKind == 1) { 1022 // Check the rest of the elements to see if they are consecutive. 1023 for (++i; i != 16; ++i) 1024 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1025 return -1; 1026 } else 1027 return -1; 1028 1029 if (ShuffleKind == 2 && isLE) 1030 ShiftAmt = 16 - ShiftAmt; 1031 1032 return ShiftAmt; 1033 } 1034 1035 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1036 /// specifies a splat of a single element that is suitable for input to 1037 /// VSPLTB/VSPLTH/VSPLTW. 1038 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1039 assert(N->getValueType(0) == MVT::v16i8 && 1040 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1041 1042 // This is a splat operation if each element of the permute is the same, and 1043 // if the value doesn't reference the second vector. 1044 unsigned ElementBase = N->getMaskElt(0); 1045 1046 // FIXME: Handle UNDEF elements too! 1047 if (ElementBase >= 16) 1048 return false; 1049 1050 // Check that the indices are consecutive, in the case of a multi-byte element 1051 // splatted with a v16i8 mask. 1052 for (unsigned i = 1; i != EltSize; ++i) 1053 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1054 return false; 1055 1056 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1057 if (N->getMaskElt(i) < 0) continue; 1058 for (unsigned j = 0; j != EltSize; ++j) 1059 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1060 return false; 1061 } 1062 return true; 1063 } 1064 1065 /// isAllNegativeZeroVector - Returns true if all elements of build_vector 1066 /// are -0.0. 1067 bool PPC::isAllNegativeZeroVector(SDNode *N) { 1068 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N); 1069 1070 APInt APVal, APUndef; 1071 unsigned BitSize; 1072 bool HasAnyUndefs; 1073 1074 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true)) 1075 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 1076 return CFP->getValueAPF().isNegZero(); 1077 1078 return false; 1079 } 1080 1081 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 1082 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 1083 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 1084 SelectionDAG &DAG) { 1085 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1086 assert(isSplatShuffleMask(SVOp, EltSize)); 1087 if (DAG.getTarget().getDataLayout()->isLittleEndian()) 1088 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 1089 else 1090 return SVOp->getMaskElt(0) / EltSize; 1091 } 1092 1093 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 1094 /// by using a vspltis[bhw] instruction of the specified element size, return 1095 /// the constant being splatted. The ByteSize field indicates the number of 1096 /// bytes of each element [124] -> [bhw]. 1097 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 1098 SDValue OpVal(nullptr, 0); 1099 1100 // If ByteSize of the splat is bigger than the element size of the 1101 // build_vector, then we have a case where we are checking for a splat where 1102 // multiple elements of the buildvector are folded together into a single 1103 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 1104 unsigned EltSize = 16/N->getNumOperands(); 1105 if (EltSize < ByteSize) { 1106 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 1107 SDValue UniquedVals[4]; 1108 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 1109 1110 // See if all of the elements in the buildvector agree across. 1111 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1112 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 1113 // If the element isn't a constant, bail fully out. 1114 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 1115 1116 1117 if (!UniquedVals[i&(Multiple-1)].getNode()) 1118 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 1119 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 1120 return SDValue(); // no match. 1121 } 1122 1123 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 1124 // either constant or undef values that are identical for each chunk. See 1125 // if these chunks can form into a larger vspltis*. 1126 1127 // Check to see if all of the leading entries are either 0 or -1. If 1128 // neither, then this won't fit into the immediate field. 1129 bool LeadingZero = true; 1130 bool LeadingOnes = true; 1131 for (unsigned i = 0; i != Multiple-1; ++i) { 1132 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 1133 1134 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue(); 1135 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue(); 1136 } 1137 // Finally, check the least significant entry. 1138 if (LeadingZero) { 1139 if (!UniquedVals[Multiple-1].getNode()) 1140 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef 1141 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 1142 if (Val < 16) 1143 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4) 1144 } 1145 if (LeadingOnes) { 1146 if (!UniquedVals[Multiple-1].getNode()) 1147 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef 1148 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 1149 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 1150 return DAG.getTargetConstant(Val, MVT::i32); 1151 } 1152 1153 return SDValue(); 1154 } 1155 1156 // Check to see if this buildvec has a single non-undef value in its elements. 1157 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1158 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 1159 if (!OpVal.getNode()) 1160 OpVal = N->getOperand(i); 1161 else if (OpVal != N->getOperand(i)) 1162 return SDValue(); 1163 } 1164 1165 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 1166 1167 unsigned ValSizeInBytes = EltSize; 1168 uint64_t Value = 0; 1169 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 1170 Value = CN->getZExtValue(); 1171 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 1172 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 1173 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 1174 } 1175 1176 // If the splat value is larger than the element value, then we can never do 1177 // this splat. The only case that we could fit the replicated bits into our 1178 // immediate field for would be zero, and we prefer to use vxor for it. 1179 if (ValSizeInBytes < ByteSize) return SDValue(); 1180 1181 // If the element value is larger than the splat value, cut it in half and 1182 // check to see if the two halves are equal. Continue doing this until we 1183 // get to ByteSize. This allows us to handle 0x01010101 as 0x01. 1184 while (ValSizeInBytes > ByteSize) { 1185 ValSizeInBytes >>= 1; 1186 1187 // If the top half equals the bottom half, we're still ok. 1188 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) != 1189 (Value & ((1 << (8*ValSizeInBytes))-1))) 1190 return SDValue(); 1191 } 1192 1193 // Properly sign extend the value. 1194 int MaskVal = SignExtend32(Value, ByteSize * 8); 1195 1196 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 1197 if (MaskVal == 0) return SDValue(); 1198 1199 // Finally, if this value fits in a 5 bit sext field, return it 1200 if (SignExtend32<5>(MaskVal) == MaskVal) 1201 return DAG.getTargetConstant(MaskVal, MVT::i32); 1202 return SDValue(); 1203 } 1204 1205 //===----------------------------------------------------------------------===// 1206 // Addressing Mode Selection 1207 //===----------------------------------------------------------------------===// 1208 1209 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 1210 /// or 64-bit immediate, and if the value can be accurately represented as a 1211 /// sign extension from a 16-bit value. If so, this returns true and the 1212 /// immediate. 1213 static bool isIntS16Immediate(SDNode *N, short &Imm) { 1214 if (!isa<ConstantSDNode>(N)) 1215 return false; 1216 1217 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue(); 1218 if (N->getValueType(0) == MVT::i32) 1219 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 1220 else 1221 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 1222 } 1223 static bool isIntS16Immediate(SDValue Op, short &Imm) { 1224 return isIntS16Immediate(Op.getNode(), Imm); 1225 } 1226 1227 1228 /// SelectAddressRegReg - Given the specified addressed, check to see if it 1229 /// can be represented as an indexed [r+r] operation. Returns false if it 1230 /// can be more efficiently represented with [r+imm]. 1231 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 1232 SDValue &Index, 1233 SelectionDAG &DAG) const { 1234 short imm = 0; 1235 if (N.getOpcode() == ISD::ADD) { 1236 if (isIntS16Immediate(N.getOperand(1), imm)) 1237 return false; // r+i 1238 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 1239 return false; // r+i 1240 1241 Base = N.getOperand(0); 1242 Index = N.getOperand(1); 1243 return true; 1244 } else if (N.getOpcode() == ISD::OR) { 1245 if (isIntS16Immediate(N.getOperand(1), imm)) 1246 return false; // r+i can fold it if we can. 1247 1248 // If this is an or of disjoint bitfields, we can codegen this as an add 1249 // (for better address arithmetic) if the LHS and RHS of the OR are provably 1250 // disjoint. 1251 APInt LHSKnownZero, LHSKnownOne; 1252 APInt RHSKnownZero, RHSKnownOne; 1253 DAG.computeKnownBits(N.getOperand(0), 1254 LHSKnownZero, LHSKnownOne); 1255 1256 if (LHSKnownZero.getBoolValue()) { 1257 DAG.computeKnownBits(N.getOperand(1), 1258 RHSKnownZero, RHSKnownOne); 1259 // If all of the bits are known zero on the LHS or RHS, the add won't 1260 // carry. 1261 if (~(LHSKnownZero | RHSKnownZero) == 0) { 1262 Base = N.getOperand(0); 1263 Index = N.getOperand(1); 1264 return true; 1265 } 1266 } 1267 } 1268 1269 return false; 1270 } 1271 1272 // If we happen to be doing an i64 load or store into a stack slot that has 1273 // less than a 4-byte alignment, then the frame-index elimination may need to 1274 // use an indexed load or store instruction (because the offset may not be a 1275 // multiple of 4). The extra register needed to hold the offset comes from the 1276 // register scavenger, and it is possible that the scavenger will need to use 1277 // an emergency spill slot. As a result, we need to make sure that a spill slot 1278 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 1279 // stack slot. 1280 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 1281 // FIXME: This does not handle the LWA case. 1282 if (VT != MVT::i64) 1283 return; 1284 1285 // NOTE: We'll exclude negative FIs here, which come from argument 1286 // lowering, because there are no known test cases triggering this problem 1287 // using packed structures (or similar). We can remove this exclusion if 1288 // we find such a test case. The reason why this is so test-case driven is 1289 // because this entire 'fixup' is only to prevent crashes (from the 1290 // register scavenger) on not-really-valid inputs. For example, if we have: 1291 // %a = alloca i1 1292 // %b = bitcast i1* %a to i64* 1293 // store i64* a, i64 b 1294 // then the store should really be marked as 'align 1', but is not. If it 1295 // were marked as 'align 1' then the indexed form would have been 1296 // instruction-selected initially, and the problem this 'fixup' is preventing 1297 // won't happen regardless. 1298 if (FrameIdx < 0) 1299 return; 1300 1301 MachineFunction &MF = DAG.getMachineFunction(); 1302 MachineFrameInfo *MFI = MF.getFrameInfo(); 1303 1304 unsigned Align = MFI->getObjectAlignment(FrameIdx); 1305 if (Align >= 4) 1306 return; 1307 1308 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1309 FuncInfo->setHasNonRISpills(); 1310 } 1311 1312 /// Returns true if the address N can be represented by a base register plus 1313 /// a signed 16-bit displacement [r+imm], and if it is not better 1314 /// represented as reg+reg. If Aligned is true, only accept displacements 1315 /// suitable for STD and friends, i.e. multiples of 4. 1316 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 1317 SDValue &Base, 1318 SelectionDAG &DAG, 1319 bool Aligned) const { 1320 // FIXME dl should come from parent load or store, not from address 1321 SDLoc dl(N); 1322 // If this can be more profitably realized as r+r, fail. 1323 if (SelectAddressRegReg(N, Disp, Base, DAG)) 1324 return false; 1325 1326 if (N.getOpcode() == ISD::ADD) { 1327 short imm = 0; 1328 if (isIntS16Immediate(N.getOperand(1), imm) && 1329 (!Aligned || (imm & 3) == 0)) { 1330 Disp = DAG.getTargetConstant(imm, N.getValueType()); 1331 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 1332 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1333 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1334 } else { 1335 Base = N.getOperand(0); 1336 } 1337 return true; // [r+i] 1338 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 1339 // Match LOAD (ADD (X, Lo(G))). 1340 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 1341 && "Cannot handle constant offsets yet!"); 1342 Disp = N.getOperand(1).getOperand(0); // The global address. 1343 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 1344 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 1345 Disp.getOpcode() == ISD::TargetConstantPool || 1346 Disp.getOpcode() == ISD::TargetJumpTable); 1347 Base = N.getOperand(0); 1348 return true; // [&g+r] 1349 } 1350 } else if (N.getOpcode() == ISD::OR) { 1351 short imm = 0; 1352 if (isIntS16Immediate(N.getOperand(1), imm) && 1353 (!Aligned || (imm & 3) == 0)) { 1354 // If this is an or of disjoint bitfields, we can codegen this as an add 1355 // (for better address arithmetic) if the LHS and RHS of the OR are 1356 // provably disjoint. 1357 APInt LHSKnownZero, LHSKnownOne; 1358 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne); 1359 1360 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 1361 // If all of the bits are known zero on the LHS or RHS, the add won't 1362 // carry. 1363 if (FrameIndexSDNode *FI = 1364 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 1365 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1366 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1367 } else { 1368 Base = N.getOperand(0); 1369 } 1370 Disp = DAG.getTargetConstant(imm, N.getValueType()); 1371 return true; 1372 } 1373 } 1374 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 1375 // Loading from a constant address. 1376 1377 // If this address fits entirely in a 16-bit sext immediate field, codegen 1378 // this as "d, 0" 1379 short Imm; 1380 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) { 1381 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0)); 1382 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 1383 CN->getValueType(0)); 1384 return true; 1385 } 1386 1387 // Handle 32-bit sext immediates with LIS + addr mode. 1388 if ((CN->getValueType(0) == MVT::i32 || 1389 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 1390 (!Aligned || (CN->getZExtValue() & 3) == 0)) { 1391 int Addr = (int)CN->getZExtValue(); 1392 1393 // Otherwise, break this down into an LIS + disp. 1394 Disp = DAG.getTargetConstant((short)Addr, MVT::i32); 1395 1396 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32); 1397 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 1398 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 1399 return true; 1400 } 1401 } 1402 1403 Disp = DAG.getTargetConstant(0, getPointerTy()); 1404 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 1405 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1406 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1407 } else 1408 Base = N; 1409 return true; // [r+0] 1410 } 1411 1412 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 1413 /// represented as an indexed [r+r] operation. 1414 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 1415 SDValue &Index, 1416 SelectionDAG &DAG) const { 1417 // Check to see if we can easily represent this as an [r+r] address. This 1418 // will fail if it thinks that the address is more profitably represented as 1419 // reg+imm, e.g. where imm = 0. 1420 if (SelectAddressRegReg(N, Base, Index, DAG)) 1421 return true; 1422 1423 // If the operand is an addition, always emit this as [r+r], since this is 1424 // better (for code size, and execution, as the memop does the add for free) 1425 // than emitting an explicit add. 1426 if (N.getOpcode() == ISD::ADD) { 1427 Base = N.getOperand(0); 1428 Index = N.getOperand(1); 1429 return true; 1430 } 1431 1432 // Otherwise, do it the hard way, using R0 as the base register. 1433 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 1434 N.getValueType()); 1435 Index = N; 1436 return true; 1437 } 1438 1439 /// getPreIndexedAddressParts - returns true by value, base pointer and 1440 /// offset pointer and addressing mode by reference if the node's address 1441 /// can be legally represented as pre-indexed load / store address. 1442 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 1443 SDValue &Offset, 1444 ISD::MemIndexedMode &AM, 1445 SelectionDAG &DAG) const { 1446 if (DisablePPCPreinc) return false; 1447 1448 bool isLoad = true; 1449 SDValue Ptr; 1450 EVT VT; 1451 unsigned Alignment; 1452 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 1453 Ptr = LD->getBasePtr(); 1454 VT = LD->getMemoryVT(); 1455 Alignment = LD->getAlignment(); 1456 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 1457 Ptr = ST->getBasePtr(); 1458 VT = ST->getMemoryVT(); 1459 Alignment = ST->getAlignment(); 1460 isLoad = false; 1461 } else 1462 return false; 1463 1464 // PowerPC doesn't have preinc load/store instructions for vectors. 1465 if (VT.isVector()) 1466 return false; 1467 1468 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 1469 1470 // Common code will reject creating a pre-inc form if the base pointer 1471 // is a frame index, or if N is a store and the base pointer is either 1472 // the same as or a predecessor of the value being stored. Check for 1473 // those situations here, and try with swapped Base/Offset instead. 1474 bool Swap = false; 1475 1476 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 1477 Swap = true; 1478 else if (!isLoad) { 1479 SDValue Val = cast<StoreSDNode>(N)->getValue(); 1480 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 1481 Swap = true; 1482 } 1483 1484 if (Swap) 1485 std::swap(Base, Offset); 1486 1487 AM = ISD::PRE_INC; 1488 return true; 1489 } 1490 1491 // LDU/STU can only handle immediates that are a multiple of 4. 1492 if (VT != MVT::i64) { 1493 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false)) 1494 return false; 1495 } else { 1496 // LDU/STU need an address with at least 4-byte alignment. 1497 if (Alignment < 4) 1498 return false; 1499 1500 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true)) 1501 return false; 1502 } 1503 1504 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 1505 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 1506 // sext i32 to i64 when addr mode is r+i. 1507 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 1508 LD->getExtensionType() == ISD::SEXTLOAD && 1509 isa<ConstantSDNode>(Offset)) 1510 return false; 1511 } 1512 1513 AM = ISD::PRE_INC; 1514 return true; 1515 } 1516 1517 //===----------------------------------------------------------------------===// 1518 // LowerOperation implementation 1519 //===----------------------------------------------------------------------===// 1520 1521 /// GetLabelAccessInfo - Return true if we should reference labels using a 1522 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags. 1523 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags, 1524 unsigned &LoOpFlags, 1525 const GlobalValue *GV = nullptr) { 1526 HiOpFlags = PPCII::MO_HA; 1527 LoOpFlags = PPCII::MO_LO; 1528 1529 // Don't use the pic base if not in PIC relocation model. 1530 bool isPIC = TM.getRelocationModel() == Reloc::PIC_; 1531 1532 if (isPIC) { 1533 HiOpFlags |= PPCII::MO_PIC_FLAG; 1534 LoOpFlags |= PPCII::MO_PIC_FLAG; 1535 } 1536 1537 // If this is a reference to a global value that requires a non-lazy-ptr, make 1538 // sure that instruction lowering adds it. 1539 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) { 1540 HiOpFlags |= PPCII::MO_NLP_FLAG; 1541 LoOpFlags |= PPCII::MO_NLP_FLAG; 1542 1543 if (GV->hasHiddenVisibility()) { 1544 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 1545 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 1546 } 1547 } 1548 1549 return isPIC; 1550 } 1551 1552 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 1553 SelectionDAG &DAG) { 1554 EVT PtrVT = HiPart.getValueType(); 1555 SDValue Zero = DAG.getConstant(0, PtrVT); 1556 SDLoc DL(HiPart); 1557 1558 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 1559 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 1560 1561 // With PIC, the first instruction is actually "GR+hi(&G)". 1562 if (isPIC) 1563 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 1564 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 1565 1566 // Generate non-pic code that has direct accesses to the constant pool. 1567 // The address of the global is just (hi(&g)+lo(&g)). 1568 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 1569 } 1570 1571 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 1572 SelectionDAG &DAG) const { 1573 EVT PtrVT = Op.getValueType(); 1574 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 1575 const Constant *C = CP->getConstVal(); 1576 1577 // 64-bit SVR4 ABI code is always position-independent. 1578 // The actual address of the GlobalValue is stored in the TOC. 1579 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 1580 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 1581 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA, 1582 DAG.getRegister(PPC::X2, MVT::i64)); 1583 } 1584 1585 unsigned MOHiFlag, MOLoFlag; 1586 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag); 1587 1588 if (isPIC && Subtarget.isSVR4ABI()) { 1589 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 1590 PPCII::MO_PIC_FLAG); 1591 SDLoc DL(CP); 1592 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA, 1593 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT)); 1594 } 1595 1596 SDValue CPIHi = 1597 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 1598 SDValue CPILo = 1599 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 1600 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG); 1601 } 1602 1603 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 1604 EVT PtrVT = Op.getValueType(); 1605 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 1606 1607 // 64-bit SVR4 ABI code is always position-independent. 1608 // The actual address of the GlobalValue is stored in the TOC. 1609 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 1610 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 1611 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA, 1612 DAG.getRegister(PPC::X2, MVT::i64)); 1613 } 1614 1615 unsigned MOHiFlag, MOLoFlag; 1616 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag); 1617 1618 if (isPIC && Subtarget.isSVR4ABI()) { 1619 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 1620 PPCII::MO_PIC_FLAG); 1621 SDLoc DL(GA); 1622 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA, 1623 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT)); 1624 } 1625 1626 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 1627 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 1628 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG); 1629 } 1630 1631 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 1632 SelectionDAG &DAG) const { 1633 EVT PtrVT = Op.getValueType(); 1634 1635 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 1636 1637 unsigned MOHiFlag, MOLoFlag; 1638 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag); 1639 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 1640 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 1641 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG); 1642 } 1643 1644 // Generate a call to __tls_get_addr for the given GOT entry Op. 1645 std::pair<SDValue,SDValue> 1646 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl, 1647 SelectionDAG &DAG) const { 1648 1649 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext()); 1650 TargetLowering::ArgListTy Args; 1651 TargetLowering::ArgListEntry Entry; 1652 Entry.Node = Op; 1653 Entry.Ty = IntPtrTy; 1654 Args.push_back(Entry); 1655 1656 TargetLowering::CallLoweringInfo CLI(DAG); 1657 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()) 1658 .setCallee(CallingConv::C, IntPtrTy, 1659 DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()), 1660 std::move(Args), 0); 1661 1662 return LowerCallTo(CLI); 1663 } 1664 1665 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 1666 SelectionDAG &DAG) const { 1667 1668 // FIXME: TLS addresses currently use medium model code sequences, 1669 // which is the most useful form. Eventually support for small and 1670 // large models could be added if users need it, at the cost of 1671 // additional complexity. 1672 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 1673 SDLoc dl(GA); 1674 const GlobalValue *GV = GA->getGlobal(); 1675 EVT PtrVT = getPointerTy(); 1676 bool is64bit = Subtarget.isPPC64(); 1677 const Module *M = DAG.getMachineFunction().getFunction()->getParent(); 1678 PICLevel::Level picLevel = M->getPICLevel(); 1679 1680 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 1681 1682 if (Model == TLSModel::LocalExec) { 1683 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1684 PPCII::MO_TPREL_HA); 1685 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1686 PPCII::MO_TPREL_LO); 1687 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2, 1688 is64bit ? MVT::i64 : MVT::i32); 1689 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 1690 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 1691 } 1692 1693 if (Model == TLSModel::InitialExec) { 1694 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 1695 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1696 PPCII::MO_TLS); 1697 SDValue GOTPtr; 1698 if (is64bit) { 1699 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 1700 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 1701 PtrVT, GOTReg, TGA); 1702 } else 1703 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 1704 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 1705 PtrVT, TGA, GOTPtr); 1706 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 1707 } 1708 1709 if (Model == TLSModel::GeneralDynamic) { 1710 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1711 PPCII::MO_TLSGD); 1712 SDValue GOTPtr; 1713 if (is64bit) { 1714 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 1715 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 1716 GOTReg, TGA); 1717 } else { 1718 if (picLevel == PICLevel::Small) 1719 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 1720 else 1721 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 1722 } 1723 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT, 1724 GOTPtr, TGA); 1725 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG); 1726 return CallResult.first; 1727 } 1728 1729 if (Model == TLSModel::LocalDynamic) { 1730 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1731 PPCII::MO_TLSLD); 1732 SDValue GOTPtr; 1733 if (is64bit) { 1734 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 1735 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 1736 GOTReg, TGA); 1737 } else { 1738 if (picLevel == PICLevel::Small) 1739 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 1740 else 1741 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 1742 } 1743 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT, 1744 GOTPtr, TGA); 1745 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG); 1746 SDValue TLSAddr = CallResult.first; 1747 SDValue Chain = CallResult.second; 1748 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT, 1749 Chain, TLSAddr, TGA); 1750 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 1751 } 1752 1753 llvm_unreachable("Unknown TLS model!"); 1754 } 1755 1756 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 1757 SelectionDAG &DAG) const { 1758 EVT PtrVT = Op.getValueType(); 1759 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 1760 SDLoc DL(GSDN); 1761 const GlobalValue *GV = GSDN->getGlobal(); 1762 1763 // 64-bit SVR4 ABI code is always position-independent. 1764 // The actual address of the GlobalValue is stored in the TOC. 1765 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 1766 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 1767 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA, 1768 DAG.getRegister(PPC::X2, MVT::i64)); 1769 } 1770 1771 unsigned MOHiFlag, MOLoFlag; 1772 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV); 1773 1774 if (isPIC && Subtarget.isSVR4ABI()) { 1775 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 1776 GSDN->getOffset(), 1777 PPCII::MO_PIC_FLAG); 1778 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA, 1779 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32)); 1780 } 1781 1782 SDValue GAHi = 1783 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 1784 SDValue GALo = 1785 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 1786 1787 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG); 1788 1789 // If the global reference is actually to a non-lazy-pointer, we have to do an 1790 // extra load to get the address of the global. 1791 if (MOHiFlag & PPCII::MO_NLP_FLAG) 1792 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(), 1793 false, false, false, 0); 1794 return Ptr; 1795 } 1796 1797 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 1798 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1799 SDLoc dl(Op); 1800 1801 if (Op.getValueType() == MVT::v2i64) { 1802 // When the operands themselves are v2i64 values, we need to do something 1803 // special because VSX has no underlying comparison operations for these. 1804 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 1805 // Equality can be handled by casting to the legal type for Altivec 1806 // comparisons, everything else needs to be expanded. 1807 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 1808 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 1809 DAG.getSetCC(dl, MVT::v4i32, 1810 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 1811 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 1812 CC)); 1813 } 1814 1815 return SDValue(); 1816 } 1817 1818 // We handle most of these in the usual way. 1819 return Op; 1820 } 1821 1822 // If we're comparing for equality to zero, expose the fact that this is 1823 // implented as a ctlz/srl pair on ppc, so that the dag combiner can 1824 // fold the new nodes. 1825 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1826 if (C->isNullValue() && CC == ISD::SETEQ) { 1827 EVT VT = Op.getOperand(0).getValueType(); 1828 SDValue Zext = Op.getOperand(0); 1829 if (VT.bitsLT(MVT::i32)) { 1830 VT = MVT::i32; 1831 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 1832 } 1833 unsigned Log2b = Log2_32(VT.getSizeInBits()); 1834 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 1835 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 1836 DAG.getConstant(Log2b, MVT::i32)); 1837 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 1838 } 1839 // Leave comparisons against 0 and -1 alone for now, since they're usually 1840 // optimized. FIXME: revisit this when we can custom lower all setcc 1841 // optimizations. 1842 if (C->isAllOnesValue() || C->isNullValue()) 1843 return SDValue(); 1844 } 1845 1846 // If we have an integer seteq/setne, turn it into a compare against zero 1847 // by xor'ing the rhs with the lhs, which is faster than setting a 1848 // condition register, reading it back out, and masking the correct bit. The 1849 // normal approach here uses sub to do this instead of xor. Using xor exposes 1850 // the result to other bit-twiddling opportunities. 1851 EVT LHSVT = Op.getOperand(0).getValueType(); 1852 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1853 EVT VT = Op.getValueType(); 1854 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 1855 Op.getOperand(1)); 1856 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC); 1857 } 1858 return SDValue(); 1859 } 1860 1861 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG, 1862 const PPCSubtarget &Subtarget) const { 1863 SDNode *Node = Op.getNode(); 1864 EVT VT = Node->getValueType(0); 1865 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1866 SDValue InChain = Node->getOperand(0); 1867 SDValue VAListPtr = Node->getOperand(1); 1868 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 1869 SDLoc dl(Node); 1870 1871 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 1872 1873 // gpr_index 1874 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 1875 VAListPtr, MachinePointerInfo(SV), MVT::i8, 1876 false, false, 0); 1877 InChain = GprIndex.getValue(1); 1878 1879 if (VT == MVT::i64) { 1880 // Check if GprIndex is even 1881 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 1882 DAG.getConstant(1, MVT::i32)); 1883 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 1884 DAG.getConstant(0, MVT::i32), ISD::SETNE); 1885 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 1886 DAG.getConstant(1, MVT::i32)); 1887 // Align GprIndex to be even if it isn't 1888 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 1889 GprIndex); 1890 } 1891 1892 // fpr index is 1 byte after gpr 1893 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 1894 DAG.getConstant(1, MVT::i32)); 1895 1896 // fpr 1897 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 1898 FprPtr, MachinePointerInfo(SV), MVT::i8, 1899 false, false, 0); 1900 InChain = FprIndex.getValue(1); 1901 1902 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 1903 DAG.getConstant(8, MVT::i32)); 1904 1905 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 1906 DAG.getConstant(4, MVT::i32)); 1907 1908 // areas 1909 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, 1910 MachinePointerInfo(), false, false, 1911 false, 0); 1912 InChain = OverflowArea.getValue(1); 1913 1914 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, 1915 MachinePointerInfo(), false, false, 1916 false, 0); 1917 InChain = RegSaveArea.getValue(1); 1918 1919 // select overflow_area if index > 8 1920 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 1921 DAG.getConstant(8, MVT::i32), ISD::SETLT); 1922 1923 // adjustment constant gpr_index * 4/8 1924 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 1925 VT.isInteger() ? GprIndex : FprIndex, 1926 DAG.getConstant(VT.isInteger() ? 4 : 8, 1927 MVT::i32)); 1928 1929 // OurReg = RegSaveArea + RegConstant 1930 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 1931 RegConstant); 1932 1933 // Floating types are 32 bytes into RegSaveArea 1934 if (VT.isFloatingPoint()) 1935 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 1936 DAG.getConstant(32, MVT::i32)); 1937 1938 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 1939 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 1940 VT.isInteger() ? GprIndex : FprIndex, 1941 DAG.getConstant(VT == MVT::i64 ? 2 : 1, 1942 MVT::i32)); 1943 1944 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 1945 VT.isInteger() ? VAListPtr : FprPtr, 1946 MachinePointerInfo(SV), 1947 MVT::i8, false, false, 0); 1948 1949 // determine if we should load from reg_save_area or overflow_area 1950 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 1951 1952 // increase overflow_area by 4/8 if gpr/fpr > 8 1953 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 1954 DAG.getConstant(VT.isInteger() ? 4 : 8, 1955 MVT::i32)); 1956 1957 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 1958 OverflowAreaPlusN); 1959 1960 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, 1961 OverflowAreaPtr, 1962 MachinePointerInfo(), 1963 MVT::i32, false, false, 0); 1964 1965 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(), 1966 false, false, false, 0); 1967 } 1968 1969 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG, 1970 const PPCSubtarget &Subtarget) const { 1971 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 1972 1973 // We have to copy the entire va_list struct: 1974 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 1975 return DAG.getMemcpy(Op.getOperand(0), Op, 1976 Op.getOperand(1), Op.getOperand(2), 1977 DAG.getConstant(12, MVT::i32), 8, false, true, 1978 MachinePointerInfo(), MachinePointerInfo()); 1979 } 1980 1981 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 1982 SelectionDAG &DAG) const { 1983 return Op.getOperand(0); 1984 } 1985 1986 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 1987 SelectionDAG &DAG) const { 1988 SDValue Chain = Op.getOperand(0); 1989 SDValue Trmp = Op.getOperand(1); // trampoline 1990 SDValue FPtr = Op.getOperand(2); // nested function 1991 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 1992 SDLoc dl(Op); 1993 1994 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1995 bool isPPC64 = (PtrVT == MVT::i64); 1996 Type *IntPtrTy = 1997 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType( 1998 *DAG.getContext()); 1999 2000 TargetLowering::ArgListTy Args; 2001 TargetLowering::ArgListEntry Entry; 2002 2003 Entry.Ty = IntPtrTy; 2004 Entry.Node = Trmp; Args.push_back(Entry); 2005 2006 // TrampSize == (isPPC64 ? 48 : 40); 2007 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, 2008 isPPC64 ? MVT::i64 : MVT::i32); 2009 Args.push_back(Entry); 2010 2011 Entry.Node = FPtr; Args.push_back(Entry); 2012 Entry.Node = Nest; Args.push_back(Entry); 2013 2014 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 2015 TargetLowering::CallLoweringInfo CLI(DAG); 2016 CLI.setDebugLoc(dl).setChain(Chain) 2017 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), 2018 DAG.getExternalSymbol("__trampoline_setup", PtrVT), 2019 std::move(Args), 0); 2020 2021 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2022 return CallResult.second; 2023 } 2024 2025 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG, 2026 const PPCSubtarget &Subtarget) const { 2027 MachineFunction &MF = DAG.getMachineFunction(); 2028 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2029 2030 SDLoc dl(Op); 2031 2032 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 2033 // vastart just stores the address of the VarArgsFrameIndex slot into the 2034 // memory location argument. 2035 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2036 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2037 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2038 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2039 MachinePointerInfo(SV), 2040 false, false, 0); 2041 } 2042 2043 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 2044 // We suppose the given va_list is already allocated. 2045 // 2046 // typedef struct { 2047 // char gpr; /* index into the array of 8 GPRs 2048 // * stored in the register save area 2049 // * gpr=0 corresponds to r3, 2050 // * gpr=1 to r4, etc. 2051 // */ 2052 // char fpr; /* index into the array of 8 FPRs 2053 // * stored in the register save area 2054 // * fpr=0 corresponds to f1, 2055 // * fpr=1 to f2, etc. 2056 // */ 2057 // char *overflow_arg_area; 2058 // /* location on stack that holds 2059 // * the next overflow argument 2060 // */ 2061 // char *reg_save_area; 2062 // /* where r3:r10 and f1:f8 (if saved) 2063 // * are stored 2064 // */ 2065 // } va_list[1]; 2066 2067 2068 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32); 2069 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32); 2070 2071 2072 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2073 2074 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 2075 PtrVT); 2076 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2077 PtrVT); 2078 2079 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 2080 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT); 2081 2082 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 2083 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT); 2084 2085 uint64_t FPROffset = 1; 2086 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT); 2087 2088 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2089 2090 // Store first byte : number of int regs 2091 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, 2092 Op.getOperand(1), 2093 MachinePointerInfo(SV), 2094 MVT::i8, false, false, 0); 2095 uint64_t nextOffset = FPROffset; 2096 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 2097 ConstFPROffset); 2098 2099 // Store second byte : number of float regs 2100 SDValue secondStore = 2101 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 2102 MachinePointerInfo(SV, nextOffset), MVT::i8, 2103 false, false, 0); 2104 nextOffset += StackOffset; 2105 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 2106 2107 // Store second word : arguments given on stack 2108 SDValue thirdStore = 2109 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 2110 MachinePointerInfo(SV, nextOffset), 2111 false, false, 0); 2112 nextOffset += FrameOffset; 2113 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 2114 2115 // Store third word : arguments given in registers 2116 return DAG.getStore(thirdStore, dl, FR, nextPtr, 2117 MachinePointerInfo(SV, nextOffset), 2118 false, false, 0); 2119 2120 } 2121 2122 #include "PPCGenCallingConv.inc" 2123 2124 // Function whose sole purpose is to kill compiler warnings 2125 // stemming from unused functions included from PPCGenCallingConv.inc. 2126 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 2127 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 2128 } 2129 2130 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 2131 CCValAssign::LocInfo &LocInfo, 2132 ISD::ArgFlagsTy &ArgFlags, 2133 CCState &State) { 2134 return true; 2135 } 2136 2137 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 2138 MVT &LocVT, 2139 CCValAssign::LocInfo &LocInfo, 2140 ISD::ArgFlagsTy &ArgFlags, 2141 CCState &State) { 2142 static const MCPhysReg ArgRegs[] = { 2143 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2144 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2145 }; 2146 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2147 2148 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs); 2149 2150 // Skip one register if the first unallocated register has an even register 2151 // number and there are still argument registers available which have not been 2152 // allocated yet. RegNum is actually an index into ArgRegs, which means we 2153 // need to skip a register if RegNum is odd. 2154 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 2155 State.AllocateReg(ArgRegs[RegNum]); 2156 } 2157 2158 // Always return false here, as this function only makes sure that the first 2159 // unallocated register has an odd register number and does not actually 2160 // allocate a register for the current argument. 2161 return false; 2162 } 2163 2164 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 2165 MVT &LocVT, 2166 CCValAssign::LocInfo &LocInfo, 2167 ISD::ArgFlagsTy &ArgFlags, 2168 CCState &State) { 2169 static const MCPhysReg ArgRegs[] = { 2170 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 2171 PPC::F8 2172 }; 2173 2174 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2175 2176 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs); 2177 2178 // If there is only one Floating-point register left we need to put both f64 2179 // values of a split ppc_fp128 value on the stack. 2180 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 2181 State.AllocateReg(ArgRegs[RegNum]); 2182 } 2183 2184 // Always return false here, as this function only makes sure that the two f64 2185 // values a ppc_fp128 value is split into are both passed in registers or both 2186 // passed on the stack and does not actually allocate a register for the 2187 // current argument. 2188 return false; 2189 } 2190 2191 /// GetFPR - Get the set of FP registers that should be allocated for arguments, 2192 /// on Darwin. 2193 static const MCPhysReg *GetFPR() { 2194 static const MCPhysReg FPR[] = { 2195 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 2196 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13 2197 }; 2198 2199 return FPR; 2200 } 2201 2202 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 2203 /// the stack. 2204 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 2205 unsigned PtrByteSize) { 2206 unsigned ArgSize = ArgVT.getStoreSize(); 2207 if (Flags.isByVal()) 2208 ArgSize = Flags.getByValSize(); 2209 2210 // Round up to multiples of the pointer size, except for array members, 2211 // which are always packed. 2212 if (!Flags.isInConsecutiveRegs()) 2213 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2214 2215 return ArgSize; 2216 } 2217 2218 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 2219 /// on the stack. 2220 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 2221 ISD::ArgFlagsTy Flags, 2222 unsigned PtrByteSize) { 2223 unsigned Align = PtrByteSize; 2224 2225 // Altivec parameters are padded to a 16 byte boundary. 2226 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 2227 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 2228 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) 2229 Align = 16; 2230 2231 // ByVal parameters are aligned as requested. 2232 if (Flags.isByVal()) { 2233 unsigned BVAlign = Flags.getByValAlign(); 2234 if (BVAlign > PtrByteSize) { 2235 if (BVAlign % PtrByteSize != 0) 2236 llvm_unreachable( 2237 "ByVal alignment is not a multiple of the pointer size"); 2238 2239 Align = BVAlign; 2240 } 2241 } 2242 2243 // Array members are always packed to their original alignment. 2244 if (Flags.isInConsecutiveRegs()) { 2245 // If the array member was split into multiple registers, the first 2246 // needs to be aligned to the size of the full type. (Except for 2247 // ppcf128, which is only aligned as its f64 components.) 2248 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 2249 Align = OrigVT.getStoreSize(); 2250 else 2251 Align = ArgVT.getStoreSize(); 2252 } 2253 2254 return Align; 2255 } 2256 2257 /// CalculateStackSlotUsed - Return whether this argument will use its 2258 /// stack slot (instead of being passed in registers). ArgOffset, 2259 /// AvailableFPRs, and AvailableVRs must hold the current argument 2260 /// position, and will be updated to account for this argument. 2261 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 2262 ISD::ArgFlagsTy Flags, 2263 unsigned PtrByteSize, 2264 unsigned LinkageSize, 2265 unsigned ParamAreaSize, 2266 unsigned &ArgOffset, 2267 unsigned &AvailableFPRs, 2268 unsigned &AvailableVRs) { 2269 bool UseMemory = false; 2270 2271 // Respect alignment of argument on the stack. 2272 unsigned Align = 2273 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 2274 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 2275 // If there's no space left in the argument save area, we must 2276 // use memory (this check also catches zero-sized arguments). 2277 if (ArgOffset >= LinkageSize + ParamAreaSize) 2278 UseMemory = true; 2279 2280 // Allocate argument on the stack. 2281 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 2282 if (Flags.isInConsecutiveRegsLast()) 2283 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2284 // If we overran the argument save area, we must use memory 2285 // (this check catches arguments passed partially in memory) 2286 if (ArgOffset > LinkageSize + ParamAreaSize) 2287 UseMemory = true; 2288 2289 // However, if the argument is actually passed in an FPR or a VR, 2290 // we don't use memory after all. 2291 if (!Flags.isByVal()) { 2292 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 2293 if (AvailableFPRs > 0) { 2294 --AvailableFPRs; 2295 return false; 2296 } 2297 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 2298 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 2299 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) 2300 if (AvailableVRs > 0) { 2301 --AvailableVRs; 2302 return false; 2303 } 2304 } 2305 2306 return UseMemory; 2307 } 2308 2309 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 2310 /// ensure minimum alignment required for target. 2311 static unsigned EnsureStackAlignment(const TargetMachine &Target, 2312 unsigned NumBytes) { 2313 unsigned TargetAlign = Target.getFrameLowering()->getStackAlignment(); 2314 unsigned AlignMask = TargetAlign - 1; 2315 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 2316 return NumBytes; 2317 } 2318 2319 SDValue 2320 PPCTargetLowering::LowerFormalArguments(SDValue Chain, 2321 CallingConv::ID CallConv, bool isVarArg, 2322 const SmallVectorImpl<ISD::InputArg> 2323 &Ins, 2324 SDLoc dl, SelectionDAG &DAG, 2325 SmallVectorImpl<SDValue> &InVals) 2326 const { 2327 if (Subtarget.isSVR4ABI()) { 2328 if (Subtarget.isPPC64()) 2329 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 2330 dl, DAG, InVals); 2331 else 2332 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 2333 dl, DAG, InVals); 2334 } else { 2335 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 2336 dl, DAG, InVals); 2337 } 2338 } 2339 2340 SDValue 2341 PPCTargetLowering::LowerFormalArguments_32SVR4( 2342 SDValue Chain, 2343 CallingConv::ID CallConv, bool isVarArg, 2344 const SmallVectorImpl<ISD::InputArg> 2345 &Ins, 2346 SDLoc dl, SelectionDAG &DAG, 2347 SmallVectorImpl<SDValue> &InVals) const { 2348 2349 // 32-bit SVR4 ABI Stack Frame Layout: 2350 // +-----------------------------------+ 2351 // +--> | Back chain | 2352 // | +-----------------------------------+ 2353 // | | Floating-point register save area | 2354 // | +-----------------------------------+ 2355 // | | General register save area | 2356 // | +-----------------------------------+ 2357 // | | CR save word | 2358 // | +-----------------------------------+ 2359 // | | VRSAVE save word | 2360 // | +-----------------------------------+ 2361 // | | Alignment padding | 2362 // | +-----------------------------------+ 2363 // | | Vector register save area | 2364 // | +-----------------------------------+ 2365 // | | Local variable space | 2366 // | +-----------------------------------+ 2367 // | | Parameter list area | 2368 // | +-----------------------------------+ 2369 // | | LR save word | 2370 // | +-----------------------------------+ 2371 // SP--> +--- | Back chain | 2372 // +-----------------------------------+ 2373 // 2374 // Specifications: 2375 // System V Application Binary Interface PowerPC Processor Supplement 2376 // AltiVec Technology Programming Interface Manual 2377 2378 MachineFunction &MF = DAG.getMachineFunction(); 2379 MachineFrameInfo *MFI = MF.getFrameInfo(); 2380 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2381 2382 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2383 // Potential tail calls could cause overwriting of argument stack slots. 2384 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 2385 (CallConv == CallingConv::Fast)); 2386 unsigned PtrByteSize = 4; 2387 2388 // Assign locations to all of the incoming arguments. 2389 SmallVector<CCValAssign, 16> ArgLocs; 2390 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 2391 getTargetMachine(), ArgLocs, *DAG.getContext()); 2392 2393 // Reserve space for the linkage area on the stack. 2394 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false); 2395 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 2396 2397 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 2398 2399 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2400 CCValAssign &VA = ArgLocs[i]; 2401 2402 // Arguments stored in registers. 2403 if (VA.isRegLoc()) { 2404 const TargetRegisterClass *RC; 2405 EVT ValVT = VA.getValVT(); 2406 2407 switch (ValVT.getSimpleVT().SimpleTy) { 2408 default: 2409 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 2410 case MVT::i1: 2411 case MVT::i32: 2412 RC = &PPC::GPRCRegClass; 2413 break; 2414 case MVT::f32: 2415 RC = &PPC::F4RCRegClass; 2416 break; 2417 case MVT::f64: 2418 if (Subtarget.hasVSX()) 2419 RC = &PPC::VSFRCRegClass; 2420 else 2421 RC = &PPC::F8RCRegClass; 2422 break; 2423 case MVT::v16i8: 2424 case MVT::v8i16: 2425 case MVT::v4i32: 2426 case MVT::v4f32: 2427 RC = &PPC::VRRCRegClass; 2428 break; 2429 case MVT::v2f64: 2430 case MVT::v2i64: 2431 RC = &PPC::VSHRCRegClass; 2432 break; 2433 } 2434 2435 // Transform the arguments stored in physical registers into virtual ones. 2436 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2437 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 2438 ValVT == MVT::i1 ? MVT::i32 : ValVT); 2439 2440 if (ValVT == MVT::i1) 2441 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 2442 2443 InVals.push_back(ArgValue); 2444 } else { 2445 // Argument stored in memory. 2446 assert(VA.isMemLoc()); 2447 2448 unsigned ArgSize = VA.getLocVT().getStoreSize(); 2449 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(), 2450 isImmutable); 2451 2452 // Create load nodes to retrieve arguments from the stack. 2453 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2454 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 2455 MachinePointerInfo(), 2456 false, false, false, 0)); 2457 } 2458 } 2459 2460 // Assign locations to all of the incoming aggregate by value arguments. 2461 // Aggregates passed by value are stored in the local variable space of the 2462 // caller's stack frame, right above the parameter list area. 2463 SmallVector<CCValAssign, 16> ByValArgLocs; 2464 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 2465 getTargetMachine(), ByValArgLocs, *DAG.getContext()); 2466 2467 // Reserve stack space for the allocations in CCInfo. 2468 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 2469 2470 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 2471 2472 // Area that is at least reserved in the caller of this function. 2473 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 2474 MinReservedArea = std::max(MinReservedArea, LinkageSize); 2475 2476 // Set the size that is at least reserved in caller of this function. Tail 2477 // call optimized function's reserved stack space needs to be aligned so that 2478 // taking the difference between two stack areas will result in an aligned 2479 // stack. 2480 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea); 2481 FuncInfo->setMinReservedArea(MinReservedArea); 2482 2483 SmallVector<SDValue, 8> MemOps; 2484 2485 // If the function takes variable number of arguments, make a frame index for 2486 // the start of the first vararg value... for expansion of llvm.va_start. 2487 if (isVarArg) { 2488 static const MCPhysReg GPArgRegs[] = { 2489 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2490 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2491 }; 2492 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 2493 2494 static const MCPhysReg FPArgRegs[] = { 2495 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 2496 PPC::F8 2497 }; 2498 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 2499 2500 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs, 2501 NumGPArgRegs)); 2502 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs, 2503 NumFPArgRegs)); 2504 2505 // Make room for NumGPArgRegs and NumFPArgRegs. 2506 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 2507 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8; 2508 2509 FuncInfo->setVarArgsStackOffset( 2510 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8, 2511 CCInfo.getNextStackOffset(), true)); 2512 2513 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false)); 2514 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2515 2516 // The fixed integer arguments of a variadic function are stored to the 2517 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing 2518 // the result of va_next. 2519 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 2520 // Get an existing live-in vreg, or add a new one. 2521 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 2522 if (!VReg) 2523 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 2524 2525 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2526 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2527 MachinePointerInfo(), false, false, 0); 2528 MemOps.push_back(Store); 2529 // Increment the address by four for the next argument to store 2530 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT); 2531 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 2532 } 2533 2534 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 2535 // is set. 2536 // The double arguments are stored to the VarArgsFrameIndex 2537 // on the stack. 2538 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 2539 // Get an existing live-in vreg, or add a new one. 2540 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 2541 if (!VReg) 2542 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 2543 2544 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 2545 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2546 MachinePointerInfo(), false, false, 0); 2547 MemOps.push_back(Store); 2548 // Increment the address by eight for the next argument to store 2549 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8, 2550 PtrVT); 2551 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 2552 } 2553 } 2554 2555 if (!MemOps.empty()) 2556 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 2557 2558 return Chain; 2559 } 2560 2561 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 2562 // value to MVT::i64 and then truncate to the correct register size. 2563 SDValue 2564 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT, 2565 SelectionDAG &DAG, SDValue ArgVal, 2566 SDLoc dl) const { 2567 if (Flags.isSExt()) 2568 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 2569 DAG.getValueType(ObjectVT)); 2570 else if (Flags.isZExt()) 2571 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 2572 DAG.getValueType(ObjectVT)); 2573 2574 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 2575 } 2576 2577 SDValue 2578 PPCTargetLowering::LowerFormalArguments_64SVR4( 2579 SDValue Chain, 2580 CallingConv::ID CallConv, bool isVarArg, 2581 const SmallVectorImpl<ISD::InputArg> 2582 &Ins, 2583 SDLoc dl, SelectionDAG &DAG, 2584 SmallVectorImpl<SDValue> &InVals) const { 2585 // TODO: add description of PPC stack frame format, or at least some docs. 2586 // 2587 bool isELFv2ABI = Subtarget.isELFv2ABI(); 2588 bool isLittleEndian = Subtarget.isLittleEndian(); 2589 MachineFunction &MF = DAG.getMachineFunction(); 2590 MachineFrameInfo *MFI = MF.getFrameInfo(); 2591 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2592 2593 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2594 // Potential tail calls could cause overwriting of argument stack slots. 2595 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 2596 (CallConv == CallingConv::Fast)); 2597 unsigned PtrByteSize = 8; 2598 2599 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false, 2600 isELFv2ABI); 2601 2602 static const MCPhysReg GPR[] = { 2603 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 2604 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 2605 }; 2606 2607 static const MCPhysReg *FPR = GetFPR(); 2608 2609 static const MCPhysReg VR[] = { 2610 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 2611 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 2612 }; 2613 static const MCPhysReg VSRH[] = { 2614 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8, 2615 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13 2616 }; 2617 2618 const unsigned Num_GPR_Regs = array_lengthof(GPR); 2619 const unsigned Num_FPR_Regs = 13; 2620 const unsigned Num_VR_Regs = array_lengthof(VR); 2621 2622 // Do a first pass over the arguments to determine whether the ABI 2623 // guarantees that our caller has allocated the parameter save area 2624 // on its stack frame. In the ELFv1 ABI, this is always the case; 2625 // in the ELFv2 ABI, it is true if this is a vararg function or if 2626 // any parameter is located in a stack slot. 2627 2628 bool HasParameterArea = !isELFv2ABI || isVarArg; 2629 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 2630 unsigned NumBytes = LinkageSize; 2631 unsigned AvailableFPRs = Num_FPR_Regs; 2632 unsigned AvailableVRs = Num_VR_Regs; 2633 for (unsigned i = 0, e = Ins.size(); i != e; ++i) 2634 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 2635 PtrByteSize, LinkageSize, ParamAreaSize, 2636 NumBytes, AvailableFPRs, AvailableVRs)) 2637 HasParameterArea = true; 2638 2639 // Add DAG nodes to load the arguments or copy them out of registers. On 2640 // entry to a function on PPC, the arguments start after the linkage area, 2641 // although the first ones are often in registers. 2642 2643 unsigned ArgOffset = LinkageSize; 2644 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0; 2645 SmallVector<SDValue, 8> MemOps; 2646 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 2647 unsigned CurArgIdx = 0; 2648 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 2649 SDValue ArgVal; 2650 bool needsLoad = false; 2651 EVT ObjectVT = Ins[ArgNo].VT; 2652 EVT OrigVT = Ins[ArgNo].ArgVT; 2653 unsigned ObjSize = ObjectVT.getStoreSize(); 2654 unsigned ArgSize = ObjSize; 2655 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 2656 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx); 2657 CurArgIdx = Ins[ArgNo].OrigArgIndex; 2658 2659 /* Respect alignment of argument on the stack. */ 2660 unsigned Align = 2661 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 2662 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 2663 unsigned CurArgOffset = ArgOffset; 2664 2665 /* Compute GPR index associated with argument offset. */ 2666 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 2667 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 2668 2669 // FIXME the codegen can be much improved in some cases. 2670 // We do not have to keep everything in memory. 2671 if (Flags.isByVal()) { 2672 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 2673 ObjSize = Flags.getByValSize(); 2674 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2675 // Empty aggregate parameters do not take up registers. Examples: 2676 // struct { } a; 2677 // union { } b; 2678 // int c[0]; 2679 // etc. However, we have to provide a place-holder in InVals, so 2680 // pretend we have an 8-byte item at the current address for that 2681 // purpose. 2682 if (!ObjSize) { 2683 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); 2684 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2685 InVals.push_back(FIN); 2686 continue; 2687 } 2688 2689 // Create a stack object covering all stack doublewords occupied 2690 // by the argument. If the argument is (fully or partially) on 2691 // the stack, or if the argument is fully in registers but the 2692 // caller has allocated the parameter save anyway, we can refer 2693 // directly to the caller's stack frame. Otherwise, create a 2694 // local copy in our own frame. 2695 int FI; 2696 if (HasParameterArea || 2697 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 2698 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true); 2699 else 2700 FI = MFI->CreateStackObject(ArgSize, Align, false); 2701 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2702 2703 // Handle aggregates smaller than 8 bytes. 2704 if (ObjSize < PtrByteSize) { 2705 // The value of the object is its address, which differs from the 2706 // address of the enclosing doubleword on big-endian systems. 2707 SDValue Arg = FIN; 2708 if (!isLittleEndian) { 2709 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT); 2710 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 2711 } 2712 InVals.push_back(Arg); 2713 2714 if (GPR_idx != Num_GPR_Regs) { 2715 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2716 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2717 SDValue Store; 2718 2719 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 2720 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 2721 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 2722 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 2723 MachinePointerInfo(FuncArg), 2724 ObjType, false, false, 0); 2725 } else { 2726 // For sizes that don't fit a truncating store (3, 5, 6, 7), 2727 // store the whole register as-is to the parameter save area 2728 // slot. 2729 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2730 MachinePointerInfo(FuncArg), 2731 false, false, 0); 2732 } 2733 2734 MemOps.push_back(Store); 2735 } 2736 // Whether we copied from a register or not, advance the offset 2737 // into the parameter save area by a full doubleword. 2738 ArgOffset += PtrByteSize; 2739 continue; 2740 } 2741 2742 // The value of the object is its address, which is the address of 2743 // its first stack doubleword. 2744 InVals.push_back(FIN); 2745 2746 // Store whatever pieces of the object are in registers to memory. 2747 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 2748 if (GPR_idx == Num_GPR_Regs) 2749 break; 2750 2751 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2752 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2753 SDValue Addr = FIN; 2754 if (j) { 2755 SDValue Off = DAG.getConstant(j, PtrVT); 2756 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 2757 } 2758 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 2759 MachinePointerInfo(FuncArg, j), 2760 false, false, 0); 2761 MemOps.push_back(Store); 2762 ++GPR_idx; 2763 } 2764 ArgOffset += ArgSize; 2765 continue; 2766 } 2767 2768 switch (ObjectVT.getSimpleVT().SimpleTy) { 2769 default: llvm_unreachable("Unhandled argument type!"); 2770 case MVT::i1: 2771 case MVT::i32: 2772 case MVT::i64: 2773 // These can be scalar arguments or elements of an integer array type 2774 // passed directly. Clang may use those instead of "byval" aggregate 2775 // types to avoid forcing arguments to memory unnecessarily. 2776 if (GPR_idx != Num_GPR_Regs) { 2777 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2778 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 2779 2780 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 2781 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 2782 // value to MVT::i64 and then truncate to the correct register size. 2783 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 2784 } else { 2785 needsLoad = true; 2786 ArgSize = PtrByteSize; 2787 } 2788 ArgOffset += 8; 2789 break; 2790 2791 case MVT::f32: 2792 case MVT::f64: 2793 // These can be scalar arguments or elements of a float array type 2794 // passed directly. The latter are used to implement ELFv2 homogenous 2795 // float aggregates. 2796 if (FPR_idx != Num_FPR_Regs) { 2797 unsigned VReg; 2798 2799 if (ObjectVT == MVT::f32) 2800 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 2801 else 2802 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ? 2803 &PPC::VSFRCRegClass : 2804 &PPC::F8RCRegClass); 2805 2806 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 2807 ++FPR_idx; 2808 } else if (GPR_idx != Num_GPR_Regs) { 2809 // This can only ever happen in the presence of f32 array types, 2810 // since otherwise we never run out of FPRs before running out 2811 // of GPRs. 2812 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2813 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 2814 2815 if (ObjectVT == MVT::f32) { 2816 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 2817 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 2818 DAG.getConstant(32, MVT::i32)); 2819 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 2820 } 2821 2822 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 2823 } else { 2824 needsLoad = true; 2825 } 2826 2827 // When passing an array of floats, the array occupies consecutive 2828 // space in the argument area; only round up to the next doubleword 2829 // at the end of the array. Otherwise, each float takes 8 bytes. 2830 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 2831 ArgOffset += ArgSize; 2832 if (Flags.isInConsecutiveRegsLast()) 2833 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2834 break; 2835 case MVT::v4f32: 2836 case MVT::v4i32: 2837 case MVT::v8i16: 2838 case MVT::v16i8: 2839 case MVT::v2f64: 2840 case MVT::v2i64: 2841 // These can be scalar arguments or elements of a vector array type 2842 // passed directly. The latter are used to implement ELFv2 homogenous 2843 // vector aggregates. 2844 if (VR_idx != Num_VR_Regs) { 2845 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ? 2846 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) : 2847 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 2848 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 2849 ++VR_idx; 2850 } else { 2851 needsLoad = true; 2852 } 2853 ArgOffset += 16; 2854 break; 2855 } 2856 2857 // We need to load the argument to a virtual register if we determined 2858 // above that we ran out of physical registers of the appropriate type. 2859 if (needsLoad) { 2860 if (ObjSize < ArgSize && !isLittleEndian) 2861 CurArgOffset += ArgSize - ObjSize; 2862 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 2863 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2864 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(), 2865 false, false, false, 0); 2866 } 2867 2868 InVals.push_back(ArgVal); 2869 } 2870 2871 // Area that is at least reserved in the caller of this function. 2872 unsigned MinReservedArea; 2873 if (HasParameterArea) 2874 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 2875 else 2876 MinReservedArea = LinkageSize; 2877 2878 // Set the size that is at least reserved in caller of this function. Tail 2879 // call optimized functions' reserved stack space needs to be aligned so that 2880 // taking the difference between two stack areas will result in an aligned 2881 // stack. 2882 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea); 2883 FuncInfo->setMinReservedArea(MinReservedArea); 2884 2885 // If the function takes variable number of arguments, make a frame index for 2886 // the start of the first vararg value... for expansion of llvm.va_start. 2887 if (isVarArg) { 2888 int Depth = ArgOffset; 2889 2890 FuncInfo->setVarArgsFrameIndex( 2891 MFI->CreateFixedObject(PtrByteSize, Depth, true)); 2892 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2893 2894 // If this function is vararg, store any remaining integer argument regs 2895 // to their spots on the stack so that they may be loaded by deferencing the 2896 // result of va_next. 2897 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 2898 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 2899 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2900 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2901 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2902 MachinePointerInfo(), false, false, 0); 2903 MemOps.push_back(Store); 2904 // Increment the address by four for the next argument to store 2905 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT); 2906 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 2907 } 2908 } 2909 2910 if (!MemOps.empty()) 2911 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 2912 2913 return Chain; 2914 } 2915 2916 SDValue 2917 PPCTargetLowering::LowerFormalArguments_Darwin( 2918 SDValue Chain, 2919 CallingConv::ID CallConv, bool isVarArg, 2920 const SmallVectorImpl<ISD::InputArg> 2921 &Ins, 2922 SDLoc dl, SelectionDAG &DAG, 2923 SmallVectorImpl<SDValue> &InVals) const { 2924 // TODO: add description of PPC stack frame format, or at least some docs. 2925 // 2926 MachineFunction &MF = DAG.getMachineFunction(); 2927 MachineFrameInfo *MFI = MF.getFrameInfo(); 2928 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2929 2930 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2931 bool isPPC64 = PtrVT == MVT::i64; 2932 // Potential tail calls could cause overwriting of argument stack slots. 2933 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 2934 (CallConv == CallingConv::Fast)); 2935 unsigned PtrByteSize = isPPC64 ? 8 : 4; 2936 2937 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true, 2938 false); 2939 unsigned ArgOffset = LinkageSize; 2940 // Area that is at least reserved in caller of this function. 2941 unsigned MinReservedArea = ArgOffset; 2942 2943 static const MCPhysReg GPR_32[] = { // 32-bit registers. 2944 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2945 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2946 }; 2947 static const MCPhysReg GPR_64[] = { // 64-bit registers. 2948 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 2949 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 2950 }; 2951 2952 static const MCPhysReg *FPR = GetFPR(); 2953 2954 static const MCPhysReg VR[] = { 2955 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 2956 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 2957 }; 2958 2959 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 2960 const unsigned Num_FPR_Regs = 13; 2961 const unsigned Num_VR_Regs = array_lengthof( VR); 2962 2963 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 2964 2965 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 2966 2967 // In 32-bit non-varargs functions, the stack space for vectors is after the 2968 // stack space for non-vectors. We do not use this space unless we have 2969 // too many vectors to fit in registers, something that only occurs in 2970 // constructed examples:), but we have to walk the arglist to figure 2971 // that out...for the pathological case, compute VecArgOffset as the 2972 // start of the vector parameter area. Computing VecArgOffset is the 2973 // entire point of the following loop. 2974 unsigned VecArgOffset = ArgOffset; 2975 if (!isVarArg && !isPPC64) { 2976 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 2977 ++ArgNo) { 2978 EVT ObjectVT = Ins[ArgNo].VT; 2979 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 2980 2981 if (Flags.isByVal()) { 2982 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 2983 unsigned ObjSize = Flags.getByValSize(); 2984 unsigned ArgSize = 2985 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2986 VecArgOffset += ArgSize; 2987 continue; 2988 } 2989 2990 switch(ObjectVT.getSimpleVT().SimpleTy) { 2991 default: llvm_unreachable("Unhandled argument type!"); 2992 case MVT::i1: 2993 case MVT::i32: 2994 case MVT::f32: 2995 VecArgOffset += 4; 2996 break; 2997 case MVT::i64: // PPC64 2998 case MVT::f64: 2999 // FIXME: We are guaranteed to be !isPPC64 at this point. 3000 // Does MVT::i64 apply? 3001 VecArgOffset += 8; 3002 break; 3003 case MVT::v4f32: 3004 case MVT::v4i32: 3005 case MVT::v8i16: 3006 case MVT::v16i8: 3007 // Nothing to do, we're only looking at Nonvector args here. 3008 break; 3009 } 3010 } 3011 } 3012 // We've found where the vector parameter area in memory is. Skip the 3013 // first 12 parameters; these don't use that memory. 3014 VecArgOffset = ((VecArgOffset+15)/16)*16; 3015 VecArgOffset += 12*16; 3016 3017 // Add DAG nodes to load the arguments or copy them out of registers. On 3018 // entry to a function on PPC, the arguments start after the linkage area, 3019 // although the first ones are often in registers. 3020 3021 SmallVector<SDValue, 8> MemOps; 3022 unsigned nAltivecParamsAtEnd = 0; 3023 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3024 unsigned CurArgIdx = 0; 3025 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3026 SDValue ArgVal; 3027 bool needsLoad = false; 3028 EVT ObjectVT = Ins[ArgNo].VT; 3029 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 3030 unsigned ArgSize = ObjSize; 3031 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3032 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx); 3033 CurArgIdx = Ins[ArgNo].OrigArgIndex; 3034 3035 unsigned CurArgOffset = ArgOffset; 3036 3037 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 3038 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 3039 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 3040 if (isVarArg || isPPC64) { 3041 MinReservedArea = ((MinReservedArea+15)/16)*16; 3042 MinReservedArea += CalculateStackSlotSize(ObjectVT, 3043 Flags, 3044 PtrByteSize); 3045 } else nAltivecParamsAtEnd++; 3046 } else 3047 // Calculate min reserved area. 3048 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 3049 Flags, 3050 PtrByteSize); 3051 3052 // FIXME the codegen can be much improved in some cases. 3053 // We do not have to keep everything in memory. 3054 if (Flags.isByVal()) { 3055 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3056 ObjSize = Flags.getByValSize(); 3057 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3058 // Objects of size 1 and 2 are right justified, everything else is 3059 // left justified. This means the memory address is adjusted forwards. 3060 if (ObjSize==1 || ObjSize==2) { 3061 CurArgOffset = CurArgOffset + (4 - ObjSize); 3062 } 3063 // The value of the object is its address. 3064 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true); 3065 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3066 InVals.push_back(FIN); 3067 if (ObjSize==1 || ObjSize==2) { 3068 if (GPR_idx != Num_GPR_Regs) { 3069 unsigned VReg; 3070 if (isPPC64) 3071 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3072 else 3073 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3074 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3075 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 3076 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 3077 MachinePointerInfo(FuncArg), 3078 ObjType, false, false, 0); 3079 MemOps.push_back(Store); 3080 ++GPR_idx; 3081 } 3082 3083 ArgOffset += PtrByteSize; 3084 3085 continue; 3086 } 3087 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3088 // Store whatever pieces of the object are in registers 3089 // to memory. ArgOffset will be the address of the beginning 3090 // of the object. 3091 if (GPR_idx != Num_GPR_Regs) { 3092 unsigned VReg; 3093 if (isPPC64) 3094 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3095 else 3096 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3097 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); 3098 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3099 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3100 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3101 MachinePointerInfo(FuncArg, j), 3102 false, false, 0); 3103 MemOps.push_back(Store); 3104 ++GPR_idx; 3105 ArgOffset += PtrByteSize; 3106 } else { 3107 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 3108 break; 3109 } 3110 } 3111 continue; 3112 } 3113 3114 switch (ObjectVT.getSimpleVT().SimpleTy) { 3115 default: llvm_unreachable("Unhandled argument type!"); 3116 case MVT::i1: 3117 case MVT::i32: 3118 if (!isPPC64) { 3119 if (GPR_idx != Num_GPR_Regs) { 3120 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3121 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3122 3123 if (ObjectVT == MVT::i1) 3124 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 3125 3126 ++GPR_idx; 3127 } else { 3128 needsLoad = true; 3129 ArgSize = PtrByteSize; 3130 } 3131 // All int arguments reserve stack space in the Darwin ABI. 3132 ArgOffset += PtrByteSize; 3133 break; 3134 } 3135 // FALLTHROUGH 3136 case MVT::i64: // PPC64 3137 if (GPR_idx != Num_GPR_Regs) { 3138 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3139 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3140 3141 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3142 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3143 // value to MVT::i64 and then truncate to the correct register size. 3144 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3145 3146 ++GPR_idx; 3147 } else { 3148 needsLoad = true; 3149 ArgSize = PtrByteSize; 3150 } 3151 // All int arguments reserve stack space in the Darwin ABI. 3152 ArgOffset += 8; 3153 break; 3154 3155 case MVT::f32: 3156 case MVT::f64: 3157 // Every 4 bytes of argument space consumes one of the GPRs available for 3158 // argument passing. 3159 if (GPR_idx != Num_GPR_Regs) { 3160 ++GPR_idx; 3161 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 3162 ++GPR_idx; 3163 } 3164 if (FPR_idx != Num_FPR_Regs) { 3165 unsigned VReg; 3166 3167 if (ObjectVT == MVT::f32) 3168 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 3169 else 3170 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 3171 3172 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3173 ++FPR_idx; 3174 } else { 3175 needsLoad = true; 3176 } 3177 3178 // All FP arguments reserve stack space in the Darwin ABI. 3179 ArgOffset += isPPC64 ? 8 : ObjSize; 3180 break; 3181 case MVT::v4f32: 3182 case MVT::v4i32: 3183 case MVT::v8i16: 3184 case MVT::v16i8: 3185 // Note that vector arguments in registers don't reserve stack space, 3186 // except in varargs functions. 3187 if (VR_idx != Num_VR_Regs) { 3188 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3189 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3190 if (isVarArg) { 3191 while ((ArgOffset % 16) != 0) { 3192 ArgOffset += PtrByteSize; 3193 if (GPR_idx != Num_GPR_Regs) 3194 GPR_idx++; 3195 } 3196 ArgOffset += 16; 3197 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 3198 } 3199 ++VR_idx; 3200 } else { 3201 if (!isVarArg && !isPPC64) { 3202 // Vectors go after all the nonvectors. 3203 CurArgOffset = VecArgOffset; 3204 VecArgOffset += 16; 3205 } else { 3206 // Vectors are aligned. 3207 ArgOffset = ((ArgOffset+15)/16)*16; 3208 CurArgOffset = ArgOffset; 3209 ArgOffset += 16; 3210 } 3211 needsLoad = true; 3212 } 3213 break; 3214 } 3215 3216 // We need to load the argument to a virtual register if we determined above 3217 // that we ran out of physical registers of the appropriate type. 3218 if (needsLoad) { 3219 int FI = MFI->CreateFixedObject(ObjSize, 3220 CurArgOffset + (ArgSize - ObjSize), 3221 isImmutable); 3222 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3223 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(), 3224 false, false, false, 0); 3225 } 3226 3227 InVals.push_back(ArgVal); 3228 } 3229 3230 // Allow for Altivec parameters at the end, if needed. 3231 if (nAltivecParamsAtEnd) { 3232 MinReservedArea = ((MinReservedArea+15)/16)*16; 3233 MinReservedArea += 16*nAltivecParamsAtEnd; 3234 } 3235 3236 // Area that is at least reserved in the caller of this function. 3237 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 3238 3239 // Set the size that is at least reserved in caller of this function. Tail 3240 // call optimized functions' reserved stack space needs to be aligned so that 3241 // taking the difference between two stack areas will result in an aligned 3242 // stack. 3243 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea); 3244 FuncInfo->setMinReservedArea(MinReservedArea); 3245 3246 // If the function takes variable number of arguments, make a frame index for 3247 // the start of the first vararg value... for expansion of llvm.va_start. 3248 if (isVarArg) { 3249 int Depth = ArgOffset; 3250 3251 FuncInfo->setVarArgsFrameIndex( 3252 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8, 3253 Depth, true)); 3254 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3255 3256 // If this function is vararg, store any remaining integer argument regs 3257 // to their spots on the stack so that they may be loaded by deferencing the 3258 // result of va_next. 3259 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 3260 unsigned VReg; 3261 3262 if (isPPC64) 3263 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3264 else 3265 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3266 3267 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3268 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3269 MachinePointerInfo(), false, false, 0); 3270 MemOps.push_back(Store); 3271 // Increment the address by four for the next argument to store 3272 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT); 3273 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3274 } 3275 } 3276 3277 if (!MemOps.empty()) 3278 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3279 3280 return Chain; 3281 } 3282 3283 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 3284 /// adjusted to accommodate the arguments for the tailcall. 3285 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 3286 unsigned ParamSize) { 3287 3288 if (!isTailCall) return 0; 3289 3290 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 3291 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 3292 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 3293 // Remember only if the new adjustement is bigger. 3294 if (SPDiff < FI->getTailCallSPDelta()) 3295 FI->setTailCallSPDelta(SPDiff); 3296 3297 return SPDiff; 3298 } 3299 3300 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 3301 /// for tail call optimization. Targets which want to do tail call 3302 /// optimization should implement this function. 3303 bool 3304 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 3305 CallingConv::ID CalleeCC, 3306 bool isVarArg, 3307 const SmallVectorImpl<ISD::InputArg> &Ins, 3308 SelectionDAG& DAG) const { 3309 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 3310 return false; 3311 3312 // Variable argument functions are not supported. 3313 if (isVarArg) 3314 return false; 3315 3316 MachineFunction &MF = DAG.getMachineFunction(); 3317 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 3318 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 3319 // Functions containing by val parameters are not supported. 3320 for (unsigned i = 0; i != Ins.size(); i++) { 3321 ISD::ArgFlagsTy Flags = Ins[i].Flags; 3322 if (Flags.isByVal()) return false; 3323 } 3324 3325 // Non-PIC/GOT tail calls are supported. 3326 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 3327 return true; 3328 3329 // At the moment we can only do local tail calls (in same module, hidden 3330 // or protected) if we are generating PIC. 3331 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 3332 return G->getGlobal()->hasHiddenVisibility() 3333 || G->getGlobal()->hasProtectedVisibility(); 3334 } 3335 3336 return false; 3337 } 3338 3339 /// isCallCompatibleAddress - Return the immediate to use if the specified 3340 /// 32-bit value is representable in the immediate field of a BxA instruction. 3341 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 3342 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 3343 if (!C) return nullptr; 3344 3345 int Addr = C->getZExtValue(); 3346 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 3347 SignExtend32<26>(Addr) != Addr) 3348 return nullptr; // Top 6 bits have to be sext of immediate. 3349 3350 return DAG.getConstant((int)C->getZExtValue() >> 2, 3351 DAG.getTargetLoweringInfo().getPointerTy()).getNode(); 3352 } 3353 3354 namespace { 3355 3356 struct TailCallArgumentInfo { 3357 SDValue Arg; 3358 SDValue FrameIdxOp; 3359 int FrameIdx; 3360 3361 TailCallArgumentInfo() : FrameIdx(0) {} 3362 }; 3363 3364 } 3365 3366 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 3367 static void 3368 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG, 3369 SDValue Chain, 3370 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 3371 SmallVectorImpl<SDValue> &MemOpChains, 3372 SDLoc dl) { 3373 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 3374 SDValue Arg = TailCallArgs[i].Arg; 3375 SDValue FIN = TailCallArgs[i].FrameIdxOp; 3376 int FI = TailCallArgs[i].FrameIdx; 3377 // Store relative to framepointer. 3378 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN, 3379 MachinePointerInfo::getFixedStack(FI), 3380 false, false, 0)); 3381 } 3382 } 3383 3384 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 3385 /// the appropriate stack slot for the tail call optimized function call. 3386 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, 3387 MachineFunction &MF, 3388 SDValue Chain, 3389 SDValue OldRetAddr, 3390 SDValue OldFP, 3391 int SPDiff, 3392 bool isPPC64, 3393 bool isDarwinABI, 3394 SDLoc dl) { 3395 if (SPDiff) { 3396 // Calculate the new stack slot for the return address. 3397 int SlotSize = isPPC64 ? 8 : 4; 3398 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64, 3399 isDarwinABI); 3400 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize, 3401 NewRetAddrLoc, true); 3402 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 3403 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 3404 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 3405 MachinePointerInfo::getFixedStack(NewRetAddr), 3406 false, false, 0); 3407 3408 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 3409 // slot as the FP is never overwritten. 3410 if (isDarwinABI) { 3411 int NewFPLoc = 3412 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI); 3413 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc, 3414 true); 3415 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 3416 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 3417 MachinePointerInfo::getFixedStack(NewFPIdx), 3418 false, false, 0); 3419 } 3420 } 3421 return Chain; 3422 } 3423 3424 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 3425 /// the position of the argument. 3426 static void 3427 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 3428 SDValue Arg, int SPDiff, unsigned ArgOffset, 3429 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 3430 int Offset = ArgOffset + SPDiff; 3431 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8; 3432 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 3433 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 3434 SDValue FIN = DAG.getFrameIndex(FI, VT); 3435 TailCallArgumentInfo Info; 3436 Info.Arg = Arg; 3437 Info.FrameIdxOp = FIN; 3438 Info.FrameIdx = FI; 3439 TailCallArguments.push_back(Info); 3440 } 3441 3442 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 3443 /// stack slot. Returns the chain as result and the loaded frame pointers in 3444 /// LROpOut/FPOpout. Used when tail calling. 3445 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG, 3446 int SPDiff, 3447 SDValue Chain, 3448 SDValue &LROpOut, 3449 SDValue &FPOpOut, 3450 bool isDarwinABI, 3451 SDLoc dl) const { 3452 if (SPDiff) { 3453 // Load the LR and FP stack slot for later adjusting. 3454 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 3455 LROpOut = getReturnAddrFrameIndex(DAG); 3456 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(), 3457 false, false, false, 0); 3458 Chain = SDValue(LROpOut.getNode(), 1); 3459 3460 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 3461 // slot as the FP is never overwritten. 3462 if (isDarwinABI) { 3463 FPOpOut = getFramePointerFrameIndex(DAG); 3464 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(), 3465 false, false, false, 0); 3466 Chain = SDValue(FPOpOut.getNode(), 1); 3467 } 3468 } 3469 return Chain; 3470 } 3471 3472 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 3473 /// by "Src" to address "Dst" of size "Size". Alignment information is 3474 /// specified by the specific parameter attribute. The copy will be passed as 3475 /// a byval function parameter. 3476 /// Sometimes what we are copying is the end of a larger object, the part that 3477 /// does not fit in registers. 3478 static SDValue 3479 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 3480 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 3481 SDLoc dl) { 3482 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 3483 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 3484 false, false, MachinePointerInfo(), 3485 MachinePointerInfo()); 3486 } 3487 3488 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 3489 /// tail calls. 3490 static void 3491 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, 3492 SDValue Arg, SDValue PtrOff, int SPDiff, 3493 unsigned ArgOffset, bool isPPC64, bool isTailCall, 3494 bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 3495 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, 3496 SDLoc dl) { 3497 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3498 if (!isTailCall) { 3499 if (isVector) { 3500 SDValue StackPtr; 3501 if (isPPC64) 3502 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 3503 else 3504 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 3505 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 3506 DAG.getConstant(ArgOffset, PtrVT)); 3507 } 3508 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, 3509 MachinePointerInfo(), false, false, 0)); 3510 // Calculate and remember argument location. 3511 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 3512 TailCallArguments); 3513 } 3514 3515 static 3516 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 3517 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes, 3518 SDValue LROp, SDValue FPOp, bool isDarwinABI, 3519 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 3520 MachineFunction &MF = DAG.getMachineFunction(); 3521 3522 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 3523 // might overwrite each other in case of tail call optimization. 3524 SmallVector<SDValue, 8> MemOpChains2; 3525 // Do not flag preceding copytoreg stuff together with the following stuff. 3526 InFlag = SDValue(); 3527 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 3528 MemOpChains2, dl); 3529 if (!MemOpChains2.empty()) 3530 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 3531 3532 // Store the return address to the appropriate stack slot. 3533 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff, 3534 isPPC64, isDarwinABI, dl); 3535 3536 // Emit callseq_end just before tailcall node. 3537 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 3538 DAG.getIntPtrConstant(0, true), InFlag, dl); 3539 InFlag = Chain.getValue(1); 3540 } 3541 3542 static 3543 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, 3544 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall, 3545 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass, 3546 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 3547 const PPCSubtarget &Subtarget) { 3548 3549 bool isPPC64 = Subtarget.isPPC64(); 3550 bool isSVR4ABI = Subtarget.isSVR4ABI(); 3551 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3552 3553 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3554 NodeTys.push_back(MVT::Other); // Returns a chain 3555 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 3556 3557 unsigned CallOpc = PPCISD::CALL; 3558 3559 bool needIndirectCall = true; 3560 if (!isSVR4ABI || !isPPC64) 3561 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 3562 // If this is an absolute destination address, use the munged value. 3563 Callee = SDValue(Dest, 0); 3564 needIndirectCall = false; 3565 } 3566 3567 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3568 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201 3569 // Use indirect calls for ALL functions calls in JIT mode, since the 3570 // far-call stubs may be outside relocation limits for a BL instruction. 3571 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) { 3572 unsigned OpFlags = 0; 3573 if ((DAG.getTarget().getRelocationModel() != Reloc::Static && 3574 (Subtarget.getTargetTriple().isMacOSX() && 3575 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) && 3576 (G->getGlobal()->isDeclaration() || 3577 G->getGlobal()->isWeakForLinker())) || 3578 (Subtarget.isTargetELF() && !isPPC64 && 3579 !G->getGlobal()->hasLocalLinkage() && 3580 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) { 3581 // PC-relative references to external symbols should go through $stub, 3582 // unless we're building with the leopard linker or later, which 3583 // automatically synthesizes these stubs. 3584 OpFlags = PPCII::MO_PLT_OR_STUB; 3585 } 3586 3587 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 3588 // every direct call is) turn it into a TargetGlobalAddress / 3589 // TargetExternalSymbol node so that legalize doesn't hack it. 3590 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 3591 Callee.getValueType(), 3592 0, OpFlags); 3593 needIndirectCall = false; 3594 } 3595 } 3596 3597 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3598 unsigned char OpFlags = 0; 3599 3600 if ((DAG.getTarget().getRelocationModel() != Reloc::Static && 3601 (Subtarget.getTargetTriple().isMacOSX() && 3602 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) || 3603 (Subtarget.isTargetELF() && !isPPC64 && 3604 DAG.getTarget().getRelocationModel() == Reloc::PIC_) ) { 3605 // PC-relative references to external symbols should go through $stub, 3606 // unless we're building with the leopard linker or later, which 3607 // automatically synthesizes these stubs. 3608 OpFlags = PPCII::MO_PLT_OR_STUB; 3609 } 3610 3611 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 3612 OpFlags); 3613 needIndirectCall = false; 3614 } 3615 3616 if (needIndirectCall) { 3617 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 3618 // to do the call, we can't use PPCISD::CALL. 3619 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 3620 3621 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 3622 // Function pointers in the 64-bit SVR4 ABI do not point to the function 3623 // entry point, but to the function descriptor (the function entry point 3624 // address is part of the function descriptor though). 3625 // The function descriptor is a three doubleword structure with the 3626 // following fields: function entry point, TOC base address and 3627 // environment pointer. 3628 // Thus for a call through a function pointer, the following actions need 3629 // to be performed: 3630 // 1. Save the TOC of the caller in the TOC save area of its stack 3631 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 3632 // 2. Load the address of the function entry point from the function 3633 // descriptor. 3634 // 3. Load the TOC of the callee from the function descriptor into r2. 3635 // 4. Load the environment pointer from the function descriptor into 3636 // r11. 3637 // 5. Branch to the function entry point address. 3638 // 6. On return of the callee, the TOC of the caller needs to be 3639 // restored (this is done in FinishCall()). 3640 // 3641 // All those operations are flagged together to ensure that no other 3642 // operations can be scheduled in between. E.g. without flagging the 3643 // operations together, a TOC access in the caller could be scheduled 3644 // between the load of the callee TOC and the branch to the callee, which 3645 // results in the TOC access going through the TOC of the callee instead 3646 // of going through the TOC of the caller, which leads to incorrect code. 3647 3648 // Load the address of the function entry point from the function 3649 // descriptor. 3650 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue); 3651 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, 3652 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 3653 Chain = LoadFuncPtr.getValue(1); 3654 InFlag = LoadFuncPtr.getValue(2); 3655 3656 // Load environment pointer into r11. 3657 // Offset of the environment pointer within the function descriptor. 3658 SDValue PtrOff = DAG.getIntPtrConstant(16); 3659 3660 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 3661 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr, 3662 InFlag); 3663 Chain = LoadEnvPtr.getValue(1); 3664 InFlag = LoadEnvPtr.getValue(2); 3665 3666 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 3667 InFlag); 3668 Chain = EnvVal.getValue(0); 3669 InFlag = EnvVal.getValue(1); 3670 3671 // Load TOC of the callee into r2. We are using a target-specific load 3672 // with r2 hard coded, because the result of a target-independent load 3673 // would never go directly into r2, since r2 is a reserved register (which 3674 // prevents the register allocator from allocating it), resulting in an 3675 // additional register being allocated and an unnecessary move instruction 3676 // being generated. 3677 VTs = DAG.getVTList(MVT::Other, MVT::Glue); 3678 SDValue TOCOff = DAG.getIntPtrConstant(8); 3679 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 3680 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, 3681 AddTOC, InFlag); 3682 Chain = LoadTOCPtr.getValue(0); 3683 InFlag = LoadTOCPtr.getValue(1); 3684 3685 MTCTROps[0] = Chain; 3686 MTCTROps[1] = LoadFuncPtr; 3687 MTCTROps[2] = InFlag; 3688 } 3689 3690 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 3691 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 3692 InFlag = Chain.getValue(1); 3693 3694 NodeTys.clear(); 3695 NodeTys.push_back(MVT::Other); 3696 NodeTys.push_back(MVT::Glue); 3697 Ops.push_back(Chain); 3698 CallOpc = PPCISD::BCTRL; 3699 Callee.setNode(nullptr); 3700 // Add use of X11 (holding environment pointer) 3701 if (isSVR4ABI && isPPC64 && !isELFv2ABI) 3702 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 3703 // Add CTR register as callee so a bctr can be emitted later. 3704 if (isTailCall) 3705 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 3706 } 3707 3708 // If this is a direct call, pass the chain and the callee. 3709 if (Callee.getNode()) { 3710 Ops.push_back(Chain); 3711 Ops.push_back(Callee); 3712 3713 // If this is a call to __tls_get_addr, find the symbol whose address 3714 // is to be taken and add it to the list. This will be used to 3715 // generate __tls_get_addr(<sym>@tlsgd) or __tls_get_addr(<sym>@tlsld). 3716 // We find the symbol by walking the chain to the CopyFromReg, walking 3717 // back from the CopyFromReg to the ADDI_TLSGD_L or ADDI_TLSLD_L, and 3718 // pulling the symbol from that node. 3719 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) 3720 if (!strcmp(S->getSymbol(), "__tls_get_addr")) { 3721 assert(!needIndirectCall && "Indirect call to __tls_get_addr???"); 3722 SDNode *AddI = Chain.getNode()->getOperand(2).getNode(); 3723 SDValue TGTAddr = AddI->getOperand(1); 3724 assert(TGTAddr.getNode()->getOpcode() == ISD::TargetGlobalTLSAddress && 3725 "Didn't find target global TLS address where we expected one"); 3726 Ops.push_back(TGTAddr); 3727 CallOpc = PPCISD::CALL_TLS; 3728 } 3729 } 3730 // If this is a tail call add stack pointer delta. 3731 if (isTailCall) 3732 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32)); 3733 3734 // Add argument registers to the end of the list so that they are known live 3735 // into the call. 3736 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 3737 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 3738 RegsToPass[i].second.getValueType())); 3739 3740 // Direct calls in the ELFv2 ABI need the TOC register live into the call. 3741 if (Callee.getNode() && isELFv2ABI) 3742 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 3743 3744 return CallOpc; 3745 } 3746 3747 static 3748 bool isLocalCall(const SDValue &Callee) 3749 { 3750 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 3751 return !G->getGlobal()->isDeclaration() && 3752 !G->getGlobal()->isWeakForLinker(); 3753 return false; 3754 } 3755 3756 SDValue 3757 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 3758 CallingConv::ID CallConv, bool isVarArg, 3759 const SmallVectorImpl<ISD::InputArg> &Ins, 3760 SDLoc dl, SelectionDAG &DAG, 3761 SmallVectorImpl<SDValue> &InVals) const { 3762 3763 SmallVector<CCValAssign, 16> RVLocs; 3764 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3765 getTargetMachine(), RVLocs, *DAG.getContext()); 3766 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); 3767 3768 // Copy all of the result registers out of their specified physreg. 3769 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 3770 CCValAssign &VA = RVLocs[i]; 3771 assert(VA.isRegLoc() && "Can only return in registers!"); 3772 3773 SDValue Val = DAG.getCopyFromReg(Chain, dl, 3774 VA.getLocReg(), VA.getLocVT(), InFlag); 3775 Chain = Val.getValue(1); 3776 InFlag = Val.getValue(2); 3777 3778 switch (VA.getLocInfo()) { 3779 default: llvm_unreachable("Unknown loc info!"); 3780 case CCValAssign::Full: break; 3781 case CCValAssign::AExt: 3782 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 3783 break; 3784 case CCValAssign::ZExt: 3785 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 3786 DAG.getValueType(VA.getValVT())); 3787 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 3788 break; 3789 case CCValAssign::SExt: 3790 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 3791 DAG.getValueType(VA.getValVT())); 3792 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 3793 break; 3794 } 3795 3796 InVals.push_back(Val); 3797 } 3798 3799 return Chain; 3800 } 3801 3802 SDValue 3803 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl, 3804 bool isTailCall, bool isVarArg, 3805 SelectionDAG &DAG, 3806 SmallVector<std::pair<unsigned, SDValue>, 8> 3807 &RegsToPass, 3808 SDValue InFlag, SDValue Chain, 3809 SDValue &Callee, 3810 int SPDiff, unsigned NumBytes, 3811 const SmallVectorImpl<ISD::InputArg> &Ins, 3812 SmallVectorImpl<SDValue> &InVals) const { 3813 3814 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3815 std::vector<EVT> NodeTys; 3816 SmallVector<SDValue, 8> Ops; 3817 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff, 3818 isTailCall, RegsToPass, Ops, NodeTys, 3819 Subtarget); 3820 3821 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 3822 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 3823 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 3824 3825 // When performing tail call optimization the callee pops its arguments off 3826 // the stack. Account for this here so these bytes can be pushed back on in 3827 // PPCFrameLowering::eliminateCallFramePseudoInstr. 3828 int BytesCalleePops = 3829 (CallConv == CallingConv::Fast && 3830 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 3831 3832 // Add a register mask operand representing the call-preserved registers. 3833 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo(); 3834 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv); 3835 assert(Mask && "Missing call preserved mask for calling convention"); 3836 Ops.push_back(DAG.getRegisterMask(Mask)); 3837 3838 if (InFlag.getNode()) 3839 Ops.push_back(InFlag); 3840 3841 // Emit tail call. 3842 if (isTailCall) { 3843 assert(((Callee.getOpcode() == ISD::Register && 3844 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 3845 Callee.getOpcode() == ISD::TargetExternalSymbol || 3846 Callee.getOpcode() == ISD::TargetGlobalAddress || 3847 isa<ConstantSDNode>(Callee)) && 3848 "Expecting an global address, external symbol, absolute value or register"); 3849 3850 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 3851 } 3852 3853 // Add a NOP immediately after the branch instruction when using the 64-bit 3854 // SVR4 ABI. At link time, if caller and callee are in a different module and 3855 // thus have a different TOC, the call will be replaced with a call to a stub 3856 // function which saves the current TOC, loads the TOC of the callee and 3857 // branches to the callee. The NOP will be replaced with a load instruction 3858 // which restores the TOC of the caller from the TOC save slot of the current 3859 // stack frame. If caller and callee belong to the same module (and have the 3860 // same TOC), the NOP will remain unchanged. 3861 3862 bool needsTOCRestore = false; 3863 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) { 3864 if (CallOpc == PPCISD::BCTRL) { 3865 // This is a call through a function pointer. 3866 // Restore the caller TOC from the save area into R2. 3867 // See PrepareCall() for more information about calls through function 3868 // pointers in the 64-bit SVR4 ABI. 3869 // We are using a target-specific load with r2 hard coded, because the 3870 // result of a target-independent load would never go directly into r2, 3871 // since r2 is a reserved register (which prevents the register allocator 3872 // from allocating it), resulting in an additional register being 3873 // allocated and an unnecessary move instruction being generated. 3874 needsTOCRestore = true; 3875 } else if ((CallOpc == PPCISD::CALL) && 3876 (!isLocalCall(Callee) || 3877 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) { 3878 // Otherwise insert NOP for non-local calls. 3879 CallOpc = PPCISD::CALL_NOP; 3880 } else if (CallOpc == PPCISD::CALL_TLS) 3881 // For 64-bit SVR4, TLS calls are always non-local. 3882 CallOpc = PPCISD::CALL_NOP_TLS; 3883 } 3884 3885 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 3886 InFlag = Chain.getValue(1); 3887 3888 if (needsTOCRestore) { 3889 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 3890 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3891 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 3892 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI); 3893 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset); 3894 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 3895 Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag); 3896 InFlag = Chain.getValue(1); 3897 } 3898 3899 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 3900 DAG.getIntPtrConstant(BytesCalleePops, true), 3901 InFlag, dl); 3902 if (!Ins.empty()) 3903 InFlag = Chain.getValue(1); 3904 3905 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 3906 Ins, dl, DAG, InVals); 3907 } 3908 3909 SDValue 3910 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 3911 SmallVectorImpl<SDValue> &InVals) const { 3912 SelectionDAG &DAG = CLI.DAG; 3913 SDLoc &dl = CLI.DL; 3914 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 3915 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 3916 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 3917 SDValue Chain = CLI.Chain; 3918 SDValue Callee = CLI.Callee; 3919 bool &isTailCall = CLI.IsTailCall; 3920 CallingConv::ID CallConv = CLI.CallConv; 3921 bool isVarArg = CLI.IsVarArg; 3922 3923 if (isTailCall) 3924 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 3925 Ins, DAG); 3926 3927 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 3928 report_fatal_error("failed to perform tail call elimination on a call " 3929 "site marked musttail"); 3930 3931 if (Subtarget.isSVR4ABI()) { 3932 if (Subtarget.isPPC64()) 3933 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 3934 isTailCall, Outs, OutVals, Ins, 3935 dl, DAG, InVals); 3936 else 3937 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 3938 isTailCall, Outs, OutVals, Ins, 3939 dl, DAG, InVals); 3940 } 3941 3942 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 3943 isTailCall, Outs, OutVals, Ins, 3944 dl, DAG, InVals); 3945 } 3946 3947 SDValue 3948 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee, 3949 CallingConv::ID CallConv, bool isVarArg, 3950 bool isTailCall, 3951 const SmallVectorImpl<ISD::OutputArg> &Outs, 3952 const SmallVectorImpl<SDValue> &OutVals, 3953 const SmallVectorImpl<ISD::InputArg> &Ins, 3954 SDLoc dl, SelectionDAG &DAG, 3955 SmallVectorImpl<SDValue> &InVals) const { 3956 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 3957 // of the 32-bit SVR4 ABI stack frame layout. 3958 3959 assert((CallConv == CallingConv::C || 3960 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 3961 3962 unsigned PtrByteSize = 4; 3963 3964 MachineFunction &MF = DAG.getMachineFunction(); 3965 3966 // Mark this function as potentially containing a function that contains a 3967 // tail call. As a consequence the frame pointer will be used for dynamicalloc 3968 // and restoring the callers stack pointer in this functions epilog. This is 3969 // done because by tail calling the called function might overwrite the value 3970 // in this function's (MF) stack pointer stack slot 0(SP). 3971 if (getTargetMachine().Options.GuaranteedTailCallOpt && 3972 CallConv == CallingConv::Fast) 3973 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 3974 3975 // Count how many bytes are to be pushed on the stack, including the linkage 3976 // area, parameter list area and the part of the local variable space which 3977 // contains copies of aggregates which are passed by value. 3978 3979 // Assign locations to all of the outgoing arguments. 3980 SmallVector<CCValAssign, 16> ArgLocs; 3981 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3982 getTargetMachine(), ArgLocs, *DAG.getContext()); 3983 3984 // Reserve space for the linkage area on the stack. 3985 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false), 3986 PtrByteSize); 3987 3988 if (isVarArg) { 3989 // Handle fixed and variable vector arguments differently. 3990 // Fixed vector arguments go into registers as long as registers are 3991 // available. Variable vector arguments always go into memory. 3992 unsigned NumArgs = Outs.size(); 3993 3994 for (unsigned i = 0; i != NumArgs; ++i) { 3995 MVT ArgVT = Outs[i].VT; 3996 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3997 bool Result; 3998 3999 if (Outs[i].IsFixed) { 4000 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 4001 CCInfo); 4002 } else { 4003 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 4004 ArgFlags, CCInfo); 4005 } 4006 4007 if (Result) { 4008 #ifndef NDEBUG 4009 errs() << "Call operand #" << i << " has unhandled type " 4010 << EVT(ArgVT).getEVTString() << "\n"; 4011 #endif 4012 llvm_unreachable(nullptr); 4013 } 4014 } 4015 } else { 4016 // All arguments are treated the same. 4017 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 4018 } 4019 4020 // Assign locations to all of the outgoing aggregate by value arguments. 4021 SmallVector<CCValAssign, 16> ByValArgLocs; 4022 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 4023 getTargetMachine(), ByValArgLocs, *DAG.getContext()); 4024 4025 // Reserve stack space for the allocations in CCInfo. 4026 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 4027 4028 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 4029 4030 // Size of the linkage area, parameter list area and the part of the local 4031 // space variable where copies of aggregates which are passed by value are 4032 // stored. 4033 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 4034 4035 // Calculate by how many bytes the stack has to be adjusted in case of tail 4036 // call optimization. 4037 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 4038 4039 // Adjust the stack pointer for the new arguments... 4040 // These operations are automatically eliminated by the prolog/epilog pass 4041 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 4042 dl); 4043 SDValue CallSeqStart = Chain; 4044 4045 // Load the return address and frame pointer so it can be moved somewhere else 4046 // later. 4047 SDValue LROp, FPOp; 4048 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false, 4049 dl); 4050 4051 // Set up a copy of the stack pointer for use loading and storing any 4052 // arguments that may not fit in the registers available for argument 4053 // passing. 4054 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4055 4056 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4057 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 4058 SmallVector<SDValue, 8> MemOpChains; 4059 4060 bool seenFloatArg = false; 4061 // Walk the register/memloc assignments, inserting copies/loads. 4062 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 4063 i != e; 4064 ++i) { 4065 CCValAssign &VA = ArgLocs[i]; 4066 SDValue Arg = OutVals[i]; 4067 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4068 4069 if (Flags.isByVal()) { 4070 // Argument is an aggregate which is passed by value, thus we need to 4071 // create a copy of it in the local variable space of the current stack 4072 // frame (which is the stack frame of the caller) and pass the address of 4073 // this copy to the callee. 4074 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 4075 CCValAssign &ByValVA = ByValArgLocs[j++]; 4076 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 4077 4078 // Memory reserved in the local variable space of the callers stack frame. 4079 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 4080 4081 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 4082 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 4083 4084 // Create a copy of the argument in the local area of the current 4085 // stack frame. 4086 SDValue MemcpyCall = 4087 CreateCopyOfByValArgument(Arg, PtrOff, 4088 CallSeqStart.getNode()->getOperand(0), 4089 Flags, DAG, dl); 4090 4091 // This must go outside the CALLSEQ_START..END. 4092 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 4093 CallSeqStart.getNode()->getOperand(1), 4094 SDLoc(MemcpyCall)); 4095 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 4096 NewCallSeqStart.getNode()); 4097 Chain = CallSeqStart = NewCallSeqStart; 4098 4099 // Pass the address of the aggregate copy on the stack either in a 4100 // physical register or in the parameter list area of the current stack 4101 // frame to the callee. 4102 Arg = PtrOff; 4103 } 4104 4105 if (VA.isRegLoc()) { 4106 if (Arg.getValueType() == MVT::i1) 4107 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); 4108 4109 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 4110 // Put argument in a physical register. 4111 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 4112 } else { 4113 // Put argument in the parameter list area of the current stack frame. 4114 assert(VA.isMemLoc()); 4115 unsigned LocMemOffset = VA.getLocMemOffset(); 4116 4117 if (!isTailCall) { 4118 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 4119 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 4120 4121 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, 4122 MachinePointerInfo(), 4123 false, false, 0)); 4124 } else { 4125 // Calculate and remember argument location. 4126 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 4127 TailCallArguments); 4128 } 4129 } 4130 } 4131 4132 if (!MemOpChains.empty()) 4133 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 4134 4135 // Build a sequence of copy-to-reg nodes chained together with token chain 4136 // and flag operands which copy the outgoing args into the appropriate regs. 4137 SDValue InFlag; 4138 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 4139 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 4140 RegsToPass[i].second, InFlag); 4141 InFlag = Chain.getValue(1); 4142 } 4143 4144 // Set CR bit 6 to true if this is a vararg call with floating args passed in 4145 // registers. 4146 if (isVarArg) { 4147 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 4148 SDValue Ops[] = { Chain, InFlag }; 4149 4150 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 4151 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 4152 4153 InFlag = Chain.getValue(1); 4154 } 4155 4156 if (isTailCall) 4157 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp, 4158 false, TailCallArguments); 4159 4160 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG, 4161 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes, 4162 Ins, InVals); 4163 } 4164 4165 // Copy an argument into memory, being careful to do this outside the 4166 // call sequence for the call to which the argument belongs. 4167 SDValue 4168 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff, 4169 SDValue CallSeqStart, 4170 ISD::ArgFlagsTy Flags, 4171 SelectionDAG &DAG, 4172 SDLoc dl) const { 4173 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 4174 CallSeqStart.getNode()->getOperand(0), 4175 Flags, DAG, dl); 4176 // The MEMCPY must go outside the CALLSEQ_START..END. 4177 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 4178 CallSeqStart.getNode()->getOperand(1), 4179 SDLoc(MemcpyCall)); 4180 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 4181 NewCallSeqStart.getNode()); 4182 return NewCallSeqStart; 4183 } 4184 4185 SDValue 4186 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee, 4187 CallingConv::ID CallConv, bool isVarArg, 4188 bool isTailCall, 4189 const SmallVectorImpl<ISD::OutputArg> &Outs, 4190 const SmallVectorImpl<SDValue> &OutVals, 4191 const SmallVectorImpl<ISD::InputArg> &Ins, 4192 SDLoc dl, SelectionDAG &DAG, 4193 SmallVectorImpl<SDValue> &InVals) const { 4194 4195 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4196 bool isLittleEndian = Subtarget.isLittleEndian(); 4197 unsigned NumOps = Outs.size(); 4198 4199 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4200 unsigned PtrByteSize = 8; 4201 4202 MachineFunction &MF = DAG.getMachineFunction(); 4203 4204 // Mark this function as potentially containing a function that contains a 4205 // tail call. As a consequence the frame pointer will be used for dynamicalloc 4206 // and restoring the callers stack pointer in this functions epilog. This is 4207 // done because by tail calling the called function might overwrite the value 4208 // in this function's (MF) stack pointer stack slot 0(SP). 4209 if (getTargetMachine().Options.GuaranteedTailCallOpt && 4210 CallConv == CallingConv::Fast) 4211 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 4212 4213 // Count how many bytes are to be pushed on the stack, including the linkage 4214 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 4215 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 4216 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 4217 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false, 4218 isELFv2ABI); 4219 unsigned NumBytes = LinkageSize; 4220 4221 // Add up all the space actually used. 4222 for (unsigned i = 0; i != NumOps; ++i) { 4223 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4224 EVT ArgVT = Outs[i].VT; 4225 EVT OrigVT = Outs[i].ArgVT; 4226 4227 /* Respect alignment of argument on the stack. */ 4228 unsigned Align = 4229 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 4230 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 4231 4232 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 4233 if (Flags.isInConsecutiveRegsLast()) 4234 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4235 } 4236 4237 unsigned NumBytesActuallyUsed = NumBytes; 4238 4239 // The prolog code of the callee may store up to 8 GPR argument registers to 4240 // the stack, allowing va_start to index over them in memory if its varargs. 4241 // Because we cannot tell if this is needed on the caller side, we have to 4242 // conservatively assume that it is needed. As such, make sure we have at 4243 // least enough stack space for the caller to store the 8 GPRs. 4244 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area. 4245 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 4246 4247 // Tail call needs the stack to be aligned. 4248 if (getTargetMachine().Options.GuaranteedTailCallOpt && 4249 CallConv == CallingConv::Fast) 4250 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes); 4251 4252 // Calculate by how many bytes the stack has to be adjusted in case of tail 4253 // call optimization. 4254 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 4255 4256 // To protect arguments on the stack from being clobbered in a tail call, 4257 // force all the loads to happen before doing any other lowering. 4258 if (isTailCall) 4259 Chain = DAG.getStackArgumentTokenFactor(Chain); 4260 4261 // Adjust the stack pointer for the new arguments... 4262 // These operations are automatically eliminated by the prolog/epilog pass 4263 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 4264 dl); 4265 SDValue CallSeqStart = Chain; 4266 4267 // Load the return address and frame pointer so it can be move somewhere else 4268 // later. 4269 SDValue LROp, FPOp; 4270 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true, 4271 dl); 4272 4273 // Set up a copy of the stack pointer for use loading and storing any 4274 // arguments that may not fit in the registers available for argument 4275 // passing. 4276 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4277 4278 // Figure out which arguments are going to go in registers, and which in 4279 // memory. Also, if this is a vararg function, floating point operations 4280 // must be stored to our stack, and loaded into integer regs as well, if 4281 // any integer regs are available for argument passing. 4282 unsigned ArgOffset = LinkageSize; 4283 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0; 4284 4285 static const MCPhysReg GPR[] = { 4286 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4287 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4288 }; 4289 static const MCPhysReg *FPR = GetFPR(); 4290 4291 static const MCPhysReg VR[] = { 4292 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4293 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4294 }; 4295 static const MCPhysReg VSRH[] = { 4296 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8, 4297 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13 4298 }; 4299 4300 const unsigned NumGPRs = array_lengthof(GPR); 4301 const unsigned NumFPRs = 13; 4302 const unsigned NumVRs = array_lengthof(VR); 4303 4304 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4305 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 4306 4307 SmallVector<SDValue, 8> MemOpChains; 4308 for (unsigned i = 0; i != NumOps; ++i) { 4309 SDValue Arg = OutVals[i]; 4310 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4311 EVT ArgVT = Outs[i].VT; 4312 EVT OrigVT = Outs[i].ArgVT; 4313 4314 /* Respect alignment of argument on the stack. */ 4315 unsigned Align = 4316 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 4317 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 4318 4319 /* Compute GPR index associated with argument offset. */ 4320 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4321 GPR_idx = std::min(GPR_idx, NumGPRs); 4322 4323 // PtrOff will be used to store the current argument to the stack if a 4324 // register cannot be found for it. 4325 SDValue PtrOff; 4326 4327 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType()); 4328 4329 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 4330 4331 // Promote integers to 64-bit values. 4332 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 4333 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 4334 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4335 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 4336 } 4337 4338 // FIXME memcpy is used way more than necessary. Correctness first. 4339 // Note: "by value" is code for passing a structure by value, not 4340 // basic types. 4341 if (Flags.isByVal()) { 4342 // Note: Size includes alignment padding, so 4343 // struct x { short a; char b; } 4344 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 4345 // These are the proper values we need for right-justifying the 4346 // aggregate in a parameter register. 4347 unsigned Size = Flags.getByValSize(); 4348 4349 // An empty aggregate parameter takes up no storage and no 4350 // registers. 4351 if (Size == 0) 4352 continue; 4353 4354 // All aggregates smaller than 8 bytes must be passed right-justified. 4355 if (Size==1 || Size==2 || Size==4) { 4356 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 4357 if (GPR_idx != NumGPRs) { 4358 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 4359 MachinePointerInfo(), VT, 4360 false, false, 0); 4361 MemOpChains.push_back(Load.getValue(1)); 4362 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load)); 4363 4364 ArgOffset += PtrByteSize; 4365 continue; 4366 } 4367 } 4368 4369 if (GPR_idx == NumGPRs && Size < 8) { 4370 SDValue AddPtr = PtrOff; 4371 if (!isLittleEndian) { 4372 SDValue Const = DAG.getConstant(PtrByteSize - Size, 4373 PtrOff.getValueType()); 4374 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 4375 } 4376 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 4377 CallSeqStart, 4378 Flags, DAG, dl); 4379 ArgOffset += PtrByteSize; 4380 continue; 4381 } 4382 // Copy entire object into memory. There are cases where gcc-generated 4383 // code assumes it is there, even if it could be put entirely into 4384 // registers. (This is not what the doc says.) 4385 4386 // FIXME: The above statement is likely due to a misunderstanding of the 4387 // documents. All arguments must be copied into the parameter area BY 4388 // THE CALLEE in the event that the callee takes the address of any 4389 // formal argument. That has not yet been implemented. However, it is 4390 // reasonable to use the stack area as a staging area for the register 4391 // load. 4392 4393 // Skip this for small aggregates, as we will use the same slot for a 4394 // right-justified copy, below. 4395 if (Size >= 8) 4396 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 4397 CallSeqStart, 4398 Flags, DAG, dl); 4399 4400 // When a register is available, pass a small aggregate right-justified. 4401 if (Size < 8 && GPR_idx != NumGPRs) { 4402 // The easiest way to get this right-justified in a register 4403 // is to copy the structure into the rightmost portion of a 4404 // local variable slot, then load the whole slot into the 4405 // register. 4406 // FIXME: The memcpy seems to produce pretty awful code for 4407 // small aggregates, particularly for packed ones. 4408 // FIXME: It would be preferable to use the slot in the 4409 // parameter save area instead of a new local variable. 4410 SDValue AddPtr = PtrOff; 4411 if (!isLittleEndian) { 4412 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType()); 4413 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 4414 } 4415 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 4416 CallSeqStart, 4417 Flags, DAG, dl); 4418 4419 // Load the slot into the register. 4420 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff, 4421 MachinePointerInfo(), 4422 false, false, false, 0); 4423 MemOpChains.push_back(Load.getValue(1)); 4424 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load)); 4425 4426 // Done with this argument. 4427 ArgOffset += PtrByteSize; 4428 continue; 4429 } 4430 4431 // For aggregates larger than PtrByteSize, copy the pieces of the 4432 // object that fit into registers from the parameter save area. 4433 for (unsigned j=0; j<Size; j+=PtrByteSize) { 4434 SDValue Const = DAG.getConstant(j, PtrOff.getValueType()); 4435 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 4436 if (GPR_idx != NumGPRs) { 4437 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 4438 MachinePointerInfo(), 4439 false, false, false, 0); 4440 MemOpChains.push_back(Load.getValue(1)); 4441 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4442 ArgOffset += PtrByteSize; 4443 } else { 4444 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 4445 break; 4446 } 4447 } 4448 continue; 4449 } 4450 4451 switch (Arg.getSimpleValueType().SimpleTy) { 4452 default: llvm_unreachable("Unexpected ValueType for argument!"); 4453 case MVT::i1: 4454 case MVT::i32: 4455 case MVT::i64: 4456 // These can be scalar arguments or elements of an integer array type 4457 // passed directly. Clang may use those instead of "byval" aggregate 4458 // types to avoid forcing arguments to memory unnecessarily. 4459 if (GPR_idx != NumGPRs) { 4460 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg)); 4461 } else { 4462 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4463 true, isTailCall, false, MemOpChains, 4464 TailCallArguments, dl); 4465 } 4466 ArgOffset += PtrByteSize; 4467 break; 4468 case MVT::f32: 4469 case MVT::f64: { 4470 // These can be scalar arguments or elements of a float array type 4471 // passed directly. The latter are used to implement ELFv2 homogenous 4472 // float aggregates. 4473 4474 // Named arguments go into FPRs first, and once they overflow, the 4475 // remaining arguments go into GPRs and then the parameter save area. 4476 // Unnamed arguments for vararg functions always go to GPRs and 4477 // then the parameter save area. For now, put all arguments to vararg 4478 // routines always in both locations (FPR *and* GPR or stack slot). 4479 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 4480 4481 // First load the argument into the next available FPR. 4482 if (FPR_idx != NumFPRs) 4483 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 4484 4485 // Next, load the argument into GPR or stack slot if needed. 4486 if (!NeedGPROrStack) 4487 ; 4488 else if (GPR_idx != NumGPRs) { 4489 // In the non-vararg case, this can only ever happen in the 4490 // presence of f32 array types, since otherwise we never run 4491 // out of FPRs before running out of GPRs. 4492 SDValue ArgVal; 4493 4494 // Double values are always passed in a single GPR. 4495 if (Arg.getValueType() != MVT::f32) { 4496 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 4497 4498 // Non-array float values are extended and passed in a GPR. 4499 } else if (!Flags.isInConsecutiveRegs()) { 4500 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 4501 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 4502 4503 // If we have an array of floats, we collect every odd element 4504 // together with its predecessor into one GPR. 4505 } else if (ArgOffset % PtrByteSize != 0) { 4506 SDValue Lo, Hi; 4507 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 4508 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 4509 if (!isLittleEndian) 4510 std::swap(Lo, Hi); 4511 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4512 4513 // The final element, if even, goes into the first half of a GPR. 4514 } else if (Flags.isInConsecutiveRegsLast()) { 4515 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 4516 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 4517 if (!isLittleEndian) 4518 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 4519 DAG.getConstant(32, MVT::i32)); 4520 4521 // Non-final even elements are skipped; they will be handled 4522 // together the with subsequent argument on the next go-around. 4523 } else 4524 ArgVal = SDValue(); 4525 4526 if (ArgVal.getNode()) 4527 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal)); 4528 } else { 4529 // Single-precision floating-point values are mapped to the 4530 // second (rightmost) word of the stack doubleword. 4531 if (Arg.getValueType() == MVT::f32 && 4532 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 4533 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType()); 4534 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 4535 } 4536 4537 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4538 true, isTailCall, false, MemOpChains, 4539 TailCallArguments, dl); 4540 } 4541 // When passing an array of floats, the array occupies consecutive 4542 // space in the argument area; only round up to the next doubleword 4543 // at the end of the array. Otherwise, each float takes 8 bytes. 4544 ArgOffset += (Arg.getValueType() == MVT::f32 && 4545 Flags.isInConsecutiveRegs()) ? 4 : 8; 4546 if (Flags.isInConsecutiveRegsLast()) 4547 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4548 break; 4549 } 4550 case MVT::v4f32: 4551 case MVT::v4i32: 4552 case MVT::v8i16: 4553 case MVT::v16i8: 4554 case MVT::v2f64: 4555 case MVT::v2i64: 4556 // These can be scalar arguments or elements of a vector array type 4557 // passed directly. The latter are used to implement ELFv2 homogenous 4558 // vector aggregates. 4559 4560 // For a varargs call, named arguments go into VRs or on the stack as 4561 // usual; unnamed arguments always go to the stack or the corresponding 4562 // GPRs when within range. For now, we always put the value in both 4563 // locations (or even all three). 4564 if (isVarArg) { 4565 // We could elide this store in the case where the object fits 4566 // entirely in R registers. Maybe later. 4567 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 4568 MachinePointerInfo(), false, false, 0); 4569 MemOpChains.push_back(Store); 4570 if (VR_idx != NumVRs) { 4571 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, 4572 MachinePointerInfo(), 4573 false, false, false, 0); 4574 MemOpChains.push_back(Load.getValue(1)); 4575 4576 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 || 4577 Arg.getSimpleValueType() == MVT::v2i64) ? 4578 VSRH[VR_idx] : VR[VR_idx]; 4579 ++VR_idx; 4580 4581 RegsToPass.push_back(std::make_pair(VReg, Load)); 4582 } 4583 ArgOffset += 16; 4584 for (unsigned i=0; i<16; i+=PtrByteSize) { 4585 if (GPR_idx == NumGPRs) 4586 break; 4587 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 4588 DAG.getConstant(i, PtrVT)); 4589 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), 4590 false, false, false, 0); 4591 MemOpChains.push_back(Load.getValue(1)); 4592 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4593 } 4594 break; 4595 } 4596 4597 // Non-varargs Altivec params go into VRs or on the stack. 4598 if (VR_idx != NumVRs) { 4599 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 || 4600 Arg.getSimpleValueType() == MVT::v2i64) ? 4601 VSRH[VR_idx] : VR[VR_idx]; 4602 ++VR_idx; 4603 4604 RegsToPass.push_back(std::make_pair(VReg, Arg)); 4605 } else { 4606 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4607 true, isTailCall, true, MemOpChains, 4608 TailCallArguments, dl); 4609 } 4610 ArgOffset += 16; 4611 break; 4612 } 4613 } 4614 4615 assert(NumBytesActuallyUsed == ArgOffset); 4616 (void)NumBytesActuallyUsed; 4617 4618 if (!MemOpChains.empty()) 4619 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 4620 4621 // Check if this is an indirect call (MTCTR/BCTRL). 4622 // See PrepareCall() for more information about calls through function 4623 // pointers in the 64-bit SVR4 ABI. 4624 if (!isTailCall && 4625 !dyn_cast<GlobalAddressSDNode>(Callee) && 4626 !dyn_cast<ExternalSymbolSDNode>(Callee)) { 4627 // Load r2 into a virtual register and store it to the TOC save area. 4628 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 4629 // TOC save area offset. 4630 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI); 4631 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset); 4632 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 4633 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(), 4634 false, false, 0); 4635 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 4636 // This does not mean the MTCTR instruction must use R12; it's easier 4637 // to model this as an extra parameter, so do that. 4638 if (isELFv2ABI) 4639 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 4640 } 4641 4642 // Build a sequence of copy-to-reg nodes chained together with token chain 4643 // and flag operands which copy the outgoing args into the appropriate regs. 4644 SDValue InFlag; 4645 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 4646 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 4647 RegsToPass[i].second, InFlag); 4648 InFlag = Chain.getValue(1); 4649 } 4650 4651 if (isTailCall) 4652 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp, 4653 FPOp, true, TailCallArguments); 4654 4655 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG, 4656 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes, 4657 Ins, InVals); 4658 } 4659 4660 SDValue 4661 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee, 4662 CallingConv::ID CallConv, bool isVarArg, 4663 bool isTailCall, 4664 const SmallVectorImpl<ISD::OutputArg> &Outs, 4665 const SmallVectorImpl<SDValue> &OutVals, 4666 const SmallVectorImpl<ISD::InputArg> &Ins, 4667 SDLoc dl, SelectionDAG &DAG, 4668 SmallVectorImpl<SDValue> &InVals) const { 4669 4670 unsigned NumOps = Outs.size(); 4671 4672 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4673 bool isPPC64 = PtrVT == MVT::i64; 4674 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4675 4676 MachineFunction &MF = DAG.getMachineFunction(); 4677 4678 // Mark this function as potentially containing a function that contains a 4679 // tail call. As a consequence the frame pointer will be used for dynamicalloc 4680 // and restoring the callers stack pointer in this functions epilog. This is 4681 // done because by tail calling the called function might overwrite the value 4682 // in this function's (MF) stack pointer stack slot 0(SP). 4683 if (getTargetMachine().Options.GuaranteedTailCallOpt && 4684 CallConv == CallingConv::Fast) 4685 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 4686 4687 // Count how many bytes are to be pushed on the stack, including the linkage 4688 // area, and parameter passing area. We start with 24/48 bytes, which is 4689 // prereserved space for [SP][CR][LR][3 x unused]. 4690 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true, 4691 false); 4692 unsigned NumBytes = LinkageSize; 4693 4694 // Add up all the space actually used. 4695 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 4696 // they all go in registers, but we must reserve stack space for them for 4697 // possible use by the caller. In varargs or 64-bit calls, parameters are 4698 // assigned stack space in order, with padding so Altivec parameters are 4699 // 16-byte aligned. 4700 unsigned nAltivecParamsAtEnd = 0; 4701 for (unsigned i = 0; i != NumOps; ++i) { 4702 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4703 EVT ArgVT = Outs[i].VT; 4704 // Varargs Altivec parameters are padded to a 16 byte boundary. 4705 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 4706 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 4707 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 4708 if (!isVarArg && !isPPC64) { 4709 // Non-varargs Altivec parameters go after all the non-Altivec 4710 // parameters; handle those later so we know how much padding we need. 4711 nAltivecParamsAtEnd++; 4712 continue; 4713 } 4714 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 4715 NumBytes = ((NumBytes+15)/16)*16; 4716 } 4717 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 4718 } 4719 4720 // Allow for Altivec parameters at the end, if needed. 4721 if (nAltivecParamsAtEnd) { 4722 NumBytes = ((NumBytes+15)/16)*16; 4723 NumBytes += 16*nAltivecParamsAtEnd; 4724 } 4725 4726 // The prolog code of the callee may store up to 8 GPR argument registers to 4727 // the stack, allowing va_start to index over them in memory if its varargs. 4728 // Because we cannot tell if this is needed on the caller side, we have to 4729 // conservatively assume that it is needed. As such, make sure we have at 4730 // least enough stack space for the caller to store the 8 GPRs. 4731 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 4732 4733 // Tail call needs the stack to be aligned. 4734 if (getTargetMachine().Options.GuaranteedTailCallOpt && 4735 CallConv == CallingConv::Fast) 4736 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes); 4737 4738 // Calculate by how many bytes the stack has to be adjusted in case of tail 4739 // call optimization. 4740 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 4741 4742 // To protect arguments on the stack from being clobbered in a tail call, 4743 // force all the loads to happen before doing any other lowering. 4744 if (isTailCall) 4745 Chain = DAG.getStackArgumentTokenFactor(Chain); 4746 4747 // Adjust the stack pointer for the new arguments... 4748 // These operations are automatically eliminated by the prolog/epilog pass 4749 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 4750 dl); 4751 SDValue CallSeqStart = Chain; 4752 4753 // Load the return address and frame pointer so it can be move somewhere else 4754 // later. 4755 SDValue LROp, FPOp; 4756 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true, 4757 dl); 4758 4759 // Set up a copy of the stack pointer for use loading and storing any 4760 // arguments that may not fit in the registers available for argument 4761 // passing. 4762 SDValue StackPtr; 4763 if (isPPC64) 4764 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4765 else 4766 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4767 4768 // Figure out which arguments are going to go in registers, and which in 4769 // memory. Also, if this is a vararg function, floating point operations 4770 // must be stored to our stack, and loaded into integer regs as well, if 4771 // any integer regs are available for argument passing. 4772 unsigned ArgOffset = LinkageSize; 4773 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4774 4775 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4776 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4777 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4778 }; 4779 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4780 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4781 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4782 }; 4783 static const MCPhysReg *FPR = GetFPR(); 4784 4785 static const MCPhysReg VR[] = { 4786 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4787 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4788 }; 4789 const unsigned NumGPRs = array_lengthof(GPR_32); 4790 const unsigned NumFPRs = 13; 4791 const unsigned NumVRs = array_lengthof(VR); 4792 4793 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4794 4795 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4796 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 4797 4798 SmallVector<SDValue, 8> MemOpChains; 4799 for (unsigned i = 0; i != NumOps; ++i) { 4800 SDValue Arg = OutVals[i]; 4801 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4802 4803 // PtrOff will be used to store the current argument to the stack if a 4804 // register cannot be found for it. 4805 SDValue PtrOff; 4806 4807 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType()); 4808 4809 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 4810 4811 // On PPC64, promote integers to 64-bit values. 4812 if (isPPC64 && Arg.getValueType() == MVT::i32) { 4813 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 4814 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4815 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 4816 } 4817 4818 // FIXME memcpy is used way more than necessary. Correctness first. 4819 // Note: "by value" is code for passing a structure by value, not 4820 // basic types. 4821 if (Flags.isByVal()) { 4822 unsigned Size = Flags.getByValSize(); 4823 // Very small objects are passed right-justified. Everything else is 4824 // passed left-justified. 4825 if (Size==1 || Size==2) { 4826 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 4827 if (GPR_idx != NumGPRs) { 4828 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 4829 MachinePointerInfo(), VT, 4830 false, false, 0); 4831 MemOpChains.push_back(Load.getValue(1)); 4832 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4833 4834 ArgOffset += PtrByteSize; 4835 } else { 4836 SDValue Const = DAG.getConstant(PtrByteSize - Size, 4837 PtrOff.getValueType()); 4838 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 4839 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 4840 CallSeqStart, 4841 Flags, DAG, dl); 4842 ArgOffset += PtrByteSize; 4843 } 4844 continue; 4845 } 4846 // Copy entire object into memory. There are cases where gcc-generated 4847 // code assumes it is there, even if it could be put entirely into 4848 // registers. (This is not what the doc says.) 4849 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 4850 CallSeqStart, 4851 Flags, DAG, dl); 4852 4853 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 4854 // copy the pieces of the object that fit into registers from the 4855 // parameter save area. 4856 for (unsigned j=0; j<Size; j+=PtrByteSize) { 4857 SDValue Const = DAG.getConstant(j, PtrOff.getValueType()); 4858 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 4859 if (GPR_idx != NumGPRs) { 4860 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 4861 MachinePointerInfo(), 4862 false, false, false, 0); 4863 MemOpChains.push_back(Load.getValue(1)); 4864 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4865 ArgOffset += PtrByteSize; 4866 } else { 4867 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 4868 break; 4869 } 4870 } 4871 continue; 4872 } 4873 4874 switch (Arg.getSimpleValueType().SimpleTy) { 4875 default: llvm_unreachable("Unexpected ValueType for argument!"); 4876 case MVT::i1: 4877 case MVT::i32: 4878 case MVT::i64: 4879 if (GPR_idx != NumGPRs) { 4880 if (Arg.getValueType() == MVT::i1) 4881 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 4882 4883 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 4884 } else { 4885 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4886 isPPC64, isTailCall, false, MemOpChains, 4887 TailCallArguments, dl); 4888 } 4889 ArgOffset += PtrByteSize; 4890 break; 4891 case MVT::f32: 4892 case MVT::f64: 4893 if (FPR_idx != NumFPRs) { 4894 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 4895 4896 if (isVarArg) { 4897 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 4898 MachinePointerInfo(), false, false, 0); 4899 MemOpChains.push_back(Store); 4900 4901 // Float varargs are always shadowed in available integer registers 4902 if (GPR_idx != NumGPRs) { 4903 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, 4904 MachinePointerInfo(), false, false, 4905 false, 0); 4906 MemOpChains.push_back(Load.getValue(1)); 4907 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4908 } 4909 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 4910 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType()); 4911 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 4912 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, 4913 MachinePointerInfo(), 4914 false, false, false, 0); 4915 MemOpChains.push_back(Load.getValue(1)); 4916 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4917 } 4918 } else { 4919 // If we have any FPRs remaining, we may also have GPRs remaining. 4920 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 4921 // GPRs. 4922 if (GPR_idx != NumGPRs) 4923 ++GPR_idx; 4924 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 4925 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 4926 ++GPR_idx; 4927 } 4928 } else 4929 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4930 isPPC64, isTailCall, false, MemOpChains, 4931 TailCallArguments, dl); 4932 if (isPPC64) 4933 ArgOffset += 8; 4934 else 4935 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 4936 break; 4937 case MVT::v4f32: 4938 case MVT::v4i32: 4939 case MVT::v8i16: 4940 case MVT::v16i8: 4941 if (isVarArg) { 4942 // These go aligned on the stack, or in the corresponding R registers 4943 // when within range. The Darwin PPC ABI doc claims they also go in 4944 // V registers; in fact gcc does this only for arguments that are 4945 // prototyped, not for those that match the ... We do it for all 4946 // arguments, seems to work. 4947 while (ArgOffset % 16 !=0) { 4948 ArgOffset += PtrByteSize; 4949 if (GPR_idx != NumGPRs) 4950 GPR_idx++; 4951 } 4952 // We could elide this store in the case where the object fits 4953 // entirely in R registers. Maybe later. 4954 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4955 DAG.getConstant(ArgOffset, PtrVT)); 4956 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 4957 MachinePointerInfo(), false, false, 0); 4958 MemOpChains.push_back(Store); 4959 if (VR_idx != NumVRs) { 4960 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, 4961 MachinePointerInfo(), 4962 false, false, false, 0); 4963 MemOpChains.push_back(Load.getValue(1)); 4964 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 4965 } 4966 ArgOffset += 16; 4967 for (unsigned i=0; i<16; i+=PtrByteSize) { 4968 if (GPR_idx == NumGPRs) 4969 break; 4970 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 4971 DAG.getConstant(i, PtrVT)); 4972 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), 4973 false, false, false, 0); 4974 MemOpChains.push_back(Load.getValue(1)); 4975 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4976 } 4977 break; 4978 } 4979 4980 // Non-varargs Altivec params generally go in registers, but have 4981 // stack space allocated at the end. 4982 if (VR_idx != NumVRs) { 4983 // Doesn't have GPR space allocated. 4984 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 4985 } else if (nAltivecParamsAtEnd==0) { 4986 // We are emitting Altivec params in order. 4987 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4988 isPPC64, isTailCall, true, MemOpChains, 4989 TailCallArguments, dl); 4990 ArgOffset += 16; 4991 } 4992 break; 4993 } 4994 } 4995 // If all Altivec parameters fit in registers, as they usually do, 4996 // they get stack space following the non-Altivec parameters. We 4997 // don't track this here because nobody below needs it. 4998 // If there are more Altivec parameters than fit in registers emit 4999 // the stores here. 5000 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 5001 unsigned j = 0; 5002 // Offset is aligned; skip 1st 12 params which go in V registers. 5003 ArgOffset = ((ArgOffset+15)/16)*16; 5004 ArgOffset += 12*16; 5005 for (unsigned i = 0; i != NumOps; ++i) { 5006 SDValue Arg = OutVals[i]; 5007 EVT ArgType = Outs[i].VT; 5008 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 5009 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 5010 if (++j > NumVRs) { 5011 SDValue PtrOff; 5012 // We are emitting Altivec params in order. 5013 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5014 isPPC64, isTailCall, true, MemOpChains, 5015 TailCallArguments, dl); 5016 ArgOffset += 16; 5017 } 5018 } 5019 } 5020 } 5021 5022 if (!MemOpChains.empty()) 5023 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5024 5025 // On Darwin, R12 must contain the address of an indirect callee. This does 5026 // not mean the MTCTR instruction must use R12; it's easier to model this as 5027 // an extra parameter, so do that. 5028 if (!isTailCall && 5029 !dyn_cast<GlobalAddressSDNode>(Callee) && 5030 !dyn_cast<ExternalSymbolSDNode>(Callee) && 5031 !isBLACompatibleAddress(Callee, DAG)) 5032 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 5033 PPC::R12), Callee)); 5034 5035 // Build a sequence of copy-to-reg nodes chained together with token chain 5036 // and flag operands which copy the outgoing args into the appropriate regs. 5037 SDValue InFlag; 5038 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5039 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5040 RegsToPass[i].second, InFlag); 5041 InFlag = Chain.getValue(1); 5042 } 5043 5044 if (isTailCall) 5045 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp, 5046 FPOp, true, TailCallArguments); 5047 5048 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG, 5049 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes, 5050 Ins, InVals); 5051 } 5052 5053 bool 5054 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 5055 MachineFunction &MF, bool isVarArg, 5056 const SmallVectorImpl<ISD::OutputArg> &Outs, 5057 LLVMContext &Context) const { 5058 SmallVector<CCValAssign, 16> RVLocs; 5059 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 5060 RVLocs, Context); 5061 return CCInfo.CheckReturn(Outs, RetCC_PPC); 5062 } 5063 5064 SDValue 5065 PPCTargetLowering::LowerReturn(SDValue Chain, 5066 CallingConv::ID CallConv, bool isVarArg, 5067 const SmallVectorImpl<ISD::OutputArg> &Outs, 5068 const SmallVectorImpl<SDValue> &OutVals, 5069 SDLoc dl, SelectionDAG &DAG) const { 5070 5071 SmallVector<CCValAssign, 16> RVLocs; 5072 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 5073 getTargetMachine(), RVLocs, *DAG.getContext()); 5074 CCInfo.AnalyzeReturn(Outs, RetCC_PPC); 5075 5076 SDValue Flag; 5077 SmallVector<SDValue, 4> RetOps(1, Chain); 5078 5079 // Copy the result values into the output registers. 5080 for (unsigned i = 0; i != RVLocs.size(); ++i) { 5081 CCValAssign &VA = RVLocs[i]; 5082 assert(VA.isRegLoc() && "Can only return in registers!"); 5083 5084 SDValue Arg = OutVals[i]; 5085 5086 switch (VA.getLocInfo()) { 5087 default: llvm_unreachable("Unknown loc info!"); 5088 case CCValAssign::Full: break; 5089 case CCValAssign::AExt: 5090 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 5091 break; 5092 case CCValAssign::ZExt: 5093 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 5094 break; 5095 case CCValAssign::SExt: 5096 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 5097 break; 5098 } 5099 5100 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 5101 Flag = Chain.getValue(1); 5102 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 5103 } 5104 5105 RetOps[0] = Chain; // Update chain. 5106 5107 // Add the flag if we have it. 5108 if (Flag.getNode()) 5109 RetOps.push_back(Flag); 5110 5111 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 5112 } 5113 5114 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG, 5115 const PPCSubtarget &Subtarget) const { 5116 // When we pop the dynamic allocation we need to restore the SP link. 5117 SDLoc dl(Op); 5118 5119 // Get the corect type for pointers. 5120 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5121 5122 // Construct the stack pointer operand. 5123 bool isPPC64 = Subtarget.isPPC64(); 5124 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 5125 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 5126 5127 // Get the operands for the STACKRESTORE. 5128 SDValue Chain = Op.getOperand(0); 5129 SDValue SaveSP = Op.getOperand(1); 5130 5131 // Load the old link SP. 5132 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr, 5133 MachinePointerInfo(), 5134 false, false, false, 0); 5135 5136 // Restore the stack pointer. 5137 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 5138 5139 // Store the old link SP. 5140 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(), 5141 false, false, 0); 5142 } 5143 5144 5145 5146 SDValue 5147 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const { 5148 MachineFunction &MF = DAG.getMachineFunction(); 5149 bool isPPC64 = Subtarget.isPPC64(); 5150 bool isDarwinABI = Subtarget.isDarwinABI(); 5151 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5152 5153 // Get current frame pointer save index. The users of this index will be 5154 // primarily DYNALLOC instructions. 5155 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 5156 int RASI = FI->getReturnAddrSaveIndex(); 5157 5158 // If the frame pointer save index hasn't been defined yet. 5159 if (!RASI) { 5160 // Find out what the fix offset of the frame pointer save area. 5161 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI); 5162 // Allocate the frame index for frame pointer save area. 5163 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true); 5164 // Save the result. 5165 FI->setReturnAddrSaveIndex(RASI); 5166 } 5167 return DAG.getFrameIndex(RASI, PtrVT); 5168 } 5169 5170 SDValue 5171 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 5172 MachineFunction &MF = DAG.getMachineFunction(); 5173 bool isPPC64 = Subtarget.isPPC64(); 5174 bool isDarwinABI = Subtarget.isDarwinABI(); 5175 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5176 5177 // Get current frame pointer save index. The users of this index will be 5178 // primarily DYNALLOC instructions. 5179 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 5180 int FPSI = FI->getFramePointerSaveIndex(); 5181 5182 // If the frame pointer save index hasn't been defined yet. 5183 if (!FPSI) { 5184 // Find out what the fix offset of the frame pointer save area. 5185 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64, 5186 isDarwinABI); 5187 5188 // Allocate the frame index for frame pointer save area. 5189 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 5190 // Save the result. 5191 FI->setFramePointerSaveIndex(FPSI); 5192 } 5193 return DAG.getFrameIndex(FPSI, PtrVT); 5194 } 5195 5196 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 5197 SelectionDAG &DAG, 5198 const PPCSubtarget &Subtarget) const { 5199 // Get the inputs. 5200 SDValue Chain = Op.getOperand(0); 5201 SDValue Size = Op.getOperand(1); 5202 SDLoc dl(Op); 5203 5204 // Get the corect type for pointers. 5205 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5206 // Negate the size. 5207 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 5208 DAG.getConstant(0, PtrVT), Size); 5209 // Construct a node for the frame pointer save index. 5210 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 5211 // Build a DYNALLOC node. 5212 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 5213 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 5214 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 5215 } 5216 5217 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 5218 SelectionDAG &DAG) const { 5219 SDLoc DL(Op); 5220 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 5221 DAG.getVTList(MVT::i32, MVT::Other), 5222 Op.getOperand(0), Op.getOperand(1)); 5223 } 5224 5225 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 5226 SelectionDAG &DAG) const { 5227 SDLoc DL(Op); 5228 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 5229 Op.getOperand(0), Op.getOperand(1)); 5230 } 5231 5232 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 5233 assert(Op.getValueType() == MVT::i1 && 5234 "Custom lowering only for i1 loads"); 5235 5236 // First, load 8 bits into 32 bits, then truncate to 1 bit. 5237 5238 SDLoc dl(Op); 5239 LoadSDNode *LD = cast<LoadSDNode>(Op); 5240 5241 SDValue Chain = LD->getChain(); 5242 SDValue BasePtr = LD->getBasePtr(); 5243 MachineMemOperand *MMO = LD->getMemOperand(); 5244 5245 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain, 5246 BasePtr, MVT::i8, MMO); 5247 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 5248 5249 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 5250 return DAG.getMergeValues(Ops, dl); 5251 } 5252 5253 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 5254 assert(Op.getOperand(1).getValueType() == MVT::i1 && 5255 "Custom lowering only for i1 stores"); 5256 5257 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 5258 5259 SDLoc dl(Op); 5260 StoreSDNode *ST = cast<StoreSDNode>(Op); 5261 5262 SDValue Chain = ST->getChain(); 5263 SDValue BasePtr = ST->getBasePtr(); 5264 SDValue Value = ST->getValue(); 5265 MachineMemOperand *MMO = ST->getMemOperand(); 5266 5267 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value); 5268 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 5269 } 5270 5271 // FIXME: Remove this once the ANDI glue bug is fixed: 5272 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 5273 assert(Op.getValueType() == MVT::i1 && 5274 "Custom lowering only for i1 results"); 5275 5276 SDLoc DL(Op); 5277 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 5278 Op.getOperand(0)); 5279 } 5280 5281 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 5282 /// possible. 5283 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 5284 // Not FP? Not a fsel. 5285 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 5286 !Op.getOperand(2).getValueType().isFloatingPoint()) 5287 return Op; 5288 5289 // We might be able to do better than this under some circumstances, but in 5290 // general, fsel-based lowering of select is a finite-math-only optimization. 5291 // For more information, see section F.3 of the 2.06 ISA specification. 5292 if (!DAG.getTarget().Options.NoInfsFPMath || 5293 !DAG.getTarget().Options.NoNaNsFPMath) 5294 return Op; 5295 5296 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5297 5298 EVT ResVT = Op.getValueType(); 5299 EVT CmpVT = Op.getOperand(0).getValueType(); 5300 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 5301 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 5302 SDLoc dl(Op); 5303 5304 // If the RHS of the comparison is a 0.0, we don't need to do the 5305 // subtraction at all. 5306 SDValue Sel1; 5307 if (isFloatingPointZero(RHS)) 5308 switch (CC) { 5309 default: break; // SETUO etc aren't handled by fsel. 5310 case ISD::SETNE: 5311 std::swap(TV, FV); 5312 case ISD::SETEQ: 5313 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 5314 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 5315 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 5316 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 5317 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 5318 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 5319 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 5320 case ISD::SETULT: 5321 case ISD::SETLT: 5322 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 5323 case ISD::SETOGE: 5324 case ISD::SETGE: 5325 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 5326 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 5327 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 5328 case ISD::SETUGT: 5329 case ISD::SETGT: 5330 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 5331 case ISD::SETOLE: 5332 case ISD::SETLE: 5333 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 5334 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 5335 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 5336 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 5337 } 5338 5339 SDValue Cmp; 5340 switch (CC) { 5341 default: break; // SETUO etc aren't handled by fsel. 5342 case ISD::SETNE: 5343 std::swap(TV, FV); 5344 case ISD::SETEQ: 5345 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 5346 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 5347 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 5348 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 5349 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 5350 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 5351 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 5352 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 5353 case ISD::SETULT: 5354 case ISD::SETLT: 5355 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 5356 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 5357 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 5358 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 5359 case ISD::SETOGE: 5360 case ISD::SETGE: 5361 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 5362 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 5363 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 5364 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 5365 case ISD::SETUGT: 5366 case ISD::SETGT: 5367 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS); 5368 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 5369 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 5370 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 5371 case ISD::SETOLE: 5372 case ISD::SETLE: 5373 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS); 5374 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 5375 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 5376 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 5377 } 5378 return Op; 5379 } 5380 5381 // FIXME: Split this code up when LegalizeDAGTypes lands. 5382 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 5383 SDLoc dl) const { 5384 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 5385 SDValue Src = Op.getOperand(0); 5386 if (Src.getValueType() == MVT::f32) 5387 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 5388 5389 SDValue Tmp; 5390 switch (Op.getSimpleValueType().SimpleTy) { 5391 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 5392 case MVT::i32: 5393 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ : 5394 (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : 5395 PPCISD::FCTIDZ), 5396 dl, MVT::f64, Src); 5397 break; 5398 case MVT::i64: 5399 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 5400 "i64 FP_TO_UINT is supported only with FPCVT"); 5401 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 5402 PPCISD::FCTIDUZ, 5403 dl, MVT::f64, Src); 5404 break; 5405 } 5406 5407 // Convert the FP value to an int value through memory. 5408 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 5409 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 5410 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 5411 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 5412 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI); 5413 5414 // Emit a store to the stack slot. 5415 SDValue Chain; 5416 if (i32Stack) { 5417 MachineFunction &MF = DAG.getMachineFunction(); 5418 MachineMemOperand *MMO = 5419 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 5420 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 5421 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 5422 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 5423 } else 5424 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, 5425 MPI, false, false, 0); 5426 5427 // Result is a load from the stack slot. If loading 4 bytes, make sure to 5428 // add in a bias. 5429 if (Op.getValueType() == MVT::i32 && !i32Stack) { 5430 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 5431 DAG.getConstant(4, FIPtr.getValueType())); 5432 MPI = MachinePointerInfo(); 5433 } 5434 5435 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI, 5436 false, false, false, 0); 5437 } 5438 5439 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 5440 SelectionDAG &DAG) const { 5441 SDLoc dl(Op); 5442 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 5443 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 5444 return SDValue(); 5445 5446 if (Op.getOperand(0).getValueType() == MVT::i1) 5447 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 5448 DAG.getConstantFP(1.0, Op.getValueType()), 5449 DAG.getConstantFP(0.0, Op.getValueType())); 5450 5451 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 5452 "UINT_TO_FP is supported only with FPCVT"); 5453 5454 // If we have FCFIDS, then use it when converting to single-precision. 5455 // Otherwise, convert to double-precision and then round. 5456 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ? 5457 (Op.getOpcode() == ISD::UINT_TO_FP ? 5458 PPCISD::FCFIDUS : PPCISD::FCFIDS) : 5459 (Op.getOpcode() == ISD::UINT_TO_FP ? 5460 PPCISD::FCFIDU : PPCISD::FCFID); 5461 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ? 5462 MVT::f32 : MVT::f64; 5463 5464 if (Op.getOperand(0).getValueType() == MVT::i64) { 5465 SDValue SINT = Op.getOperand(0); 5466 // When converting to single-precision, we actually need to convert 5467 // to double-precision first and then round to single-precision. 5468 // To avoid double-rounding effects during that operation, we have 5469 // to prepare the input operand. Bits that might be truncated when 5470 // converting to double-precision are replaced by a bit that won't 5471 // be lost at this stage, but is below the single-precision rounding 5472 // position. 5473 // 5474 // However, if -enable-unsafe-fp-math is in effect, accept double 5475 // rounding to avoid the extra overhead. 5476 if (Op.getValueType() == MVT::f32 && 5477 !Subtarget.hasFPCVT() && 5478 !DAG.getTarget().Options.UnsafeFPMath) { 5479 5480 // Twiddle input to make sure the low 11 bits are zero. (If this 5481 // is the case, we are guaranteed the value will fit into the 53 bit 5482 // mantissa of an IEEE double-precision value without rounding.) 5483 // If any of those low 11 bits were not zero originally, make sure 5484 // bit 12 (value 2048) is set instead, so that the final rounding 5485 // to single-precision gets the correct result. 5486 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 5487 SINT, DAG.getConstant(2047, MVT::i64)); 5488 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 5489 Round, DAG.getConstant(2047, MVT::i64)); 5490 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 5491 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 5492 Round, DAG.getConstant(-2048, MVT::i64)); 5493 5494 // However, we cannot use that value unconditionally: if the magnitude 5495 // of the input value is small, the bit-twiddling we did above might 5496 // end up visibly changing the output. Fortunately, in that case, we 5497 // don't need to twiddle bits since the original input will convert 5498 // exactly to double-precision floating-point already. Therefore, 5499 // construct a conditional to use the original value if the top 11 5500 // bits are all sign-bit copies, and use the rounded value computed 5501 // above otherwise. 5502 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 5503 SINT, DAG.getConstant(53, MVT::i32)); 5504 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 5505 Cond, DAG.getConstant(1, MVT::i64)); 5506 Cond = DAG.getSetCC(dl, MVT::i32, 5507 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT); 5508 5509 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 5510 } 5511 5512 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 5513 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 5514 5515 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 5516 FP = DAG.getNode(ISD::FP_ROUND, dl, 5517 MVT::f32, FP, DAG.getIntPtrConstant(0)); 5518 return FP; 5519 } 5520 5521 assert(Op.getOperand(0).getValueType() == MVT::i32 && 5522 "Unhandled INT_TO_FP type in custom expander!"); 5523 // Since we only generate this in 64-bit mode, we can take advantage of 5524 // 64-bit registers. In particular, sign extend the input value into the 5525 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 5526 // then lfd it and fcfid it. 5527 MachineFunction &MF = DAG.getMachineFunction(); 5528 MachineFrameInfo *FrameInfo = MF.getFrameInfo(); 5529 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5530 5531 SDValue Ld; 5532 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 5533 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false); 5534 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 5535 5536 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 5537 MachinePointerInfo::getFixedStack(FrameIdx), 5538 false, false, 0); 5539 5540 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 5541 "Expected an i32 store"); 5542 MachineMemOperand *MMO = 5543 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx), 5544 MachineMemOperand::MOLoad, 4, 4); 5545 SDValue Ops[] = { Store, FIdx }; 5546 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 5547 PPCISD::LFIWZX : PPCISD::LFIWAX, 5548 dl, DAG.getVTList(MVT::f64, MVT::Other), 5549 Ops, MVT::i32, MMO); 5550 } else { 5551 assert(Subtarget.isPPC64() && 5552 "i32->FP without LFIWAX supported only on PPC64"); 5553 5554 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false); 5555 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 5556 5557 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 5558 Op.getOperand(0)); 5559 5560 // STD the extended value into the stack slot. 5561 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx, 5562 MachinePointerInfo::getFixedStack(FrameIdx), 5563 false, false, 0); 5564 5565 // Load the value as a double. 5566 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, 5567 MachinePointerInfo::getFixedStack(FrameIdx), 5568 false, false, false, 0); 5569 } 5570 5571 // FCFID it and return it. 5572 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 5573 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 5574 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0)); 5575 return FP; 5576 } 5577 5578 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5579 SelectionDAG &DAG) const { 5580 SDLoc dl(Op); 5581 /* 5582 The rounding mode is in bits 30:31 of FPSR, and has the following 5583 settings: 5584 00 Round to nearest 5585 01 Round to 0 5586 10 Round to +inf 5587 11 Round to -inf 5588 5589 FLT_ROUNDS, on the other hand, expects the following: 5590 -1 Undefined 5591 0 Round to 0 5592 1 Round to nearest 5593 2 Round to +inf 5594 3 Round to -inf 5595 5596 To perform the conversion, we do: 5597 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 5598 */ 5599 5600 MachineFunction &MF = DAG.getMachineFunction(); 5601 EVT VT = Op.getValueType(); 5602 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5603 5604 // Save FP Control Word to register 5605 EVT NodeTys[] = { 5606 MVT::f64, // return register 5607 MVT::Glue // unused in this context 5608 }; 5609 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 5610 5611 // Save FP register to stack slot 5612 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false); 5613 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 5614 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, 5615 StackSlot, MachinePointerInfo(), false, false,0); 5616 5617 // Load FP Control Word from low 32 bits of stack slot. 5618 SDValue Four = DAG.getConstant(4, PtrVT); 5619 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 5620 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(), 5621 false, false, false, 0); 5622 5623 // Transform as necessary 5624 SDValue CWD1 = 5625 DAG.getNode(ISD::AND, dl, MVT::i32, 5626 CWD, DAG.getConstant(3, MVT::i32)); 5627 SDValue CWD2 = 5628 DAG.getNode(ISD::SRL, dl, MVT::i32, 5629 DAG.getNode(ISD::AND, dl, MVT::i32, 5630 DAG.getNode(ISD::XOR, dl, MVT::i32, 5631 CWD, DAG.getConstant(3, MVT::i32)), 5632 DAG.getConstant(3, MVT::i32)), 5633 DAG.getConstant(1, MVT::i32)); 5634 5635 SDValue RetVal = 5636 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 5637 5638 return DAG.getNode((VT.getSizeInBits() < 16 ? 5639 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 5640 } 5641 5642 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 5643 EVT VT = Op.getValueType(); 5644 unsigned BitWidth = VT.getSizeInBits(); 5645 SDLoc dl(Op); 5646 assert(Op.getNumOperands() == 3 && 5647 VT == Op.getOperand(1).getValueType() && 5648 "Unexpected SHL!"); 5649 5650 // Expand into a bunch of logical ops. Note that these ops 5651 // depend on the PPC behavior for oversized shift amounts. 5652 SDValue Lo = Op.getOperand(0); 5653 SDValue Hi = Op.getOperand(1); 5654 SDValue Amt = Op.getOperand(2); 5655 EVT AmtVT = Amt.getValueType(); 5656 5657 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 5658 DAG.getConstant(BitWidth, AmtVT), Amt); 5659 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 5660 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 5661 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 5662 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 5663 DAG.getConstant(-BitWidth, AmtVT)); 5664 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 5665 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 5666 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 5667 SDValue OutOps[] = { OutLo, OutHi }; 5668 return DAG.getMergeValues(OutOps, dl); 5669 } 5670 5671 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 5672 EVT VT = Op.getValueType(); 5673 SDLoc dl(Op); 5674 unsigned BitWidth = VT.getSizeInBits(); 5675 assert(Op.getNumOperands() == 3 && 5676 VT == Op.getOperand(1).getValueType() && 5677 "Unexpected SRL!"); 5678 5679 // Expand into a bunch of logical ops. Note that these ops 5680 // depend on the PPC behavior for oversized shift amounts. 5681 SDValue Lo = Op.getOperand(0); 5682 SDValue Hi = Op.getOperand(1); 5683 SDValue Amt = Op.getOperand(2); 5684 EVT AmtVT = Amt.getValueType(); 5685 5686 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 5687 DAG.getConstant(BitWidth, AmtVT), Amt); 5688 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 5689 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 5690 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 5691 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 5692 DAG.getConstant(-BitWidth, AmtVT)); 5693 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 5694 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 5695 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 5696 SDValue OutOps[] = { OutLo, OutHi }; 5697 return DAG.getMergeValues(OutOps, dl); 5698 } 5699 5700 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 5701 SDLoc dl(Op); 5702 EVT VT = Op.getValueType(); 5703 unsigned BitWidth = VT.getSizeInBits(); 5704 assert(Op.getNumOperands() == 3 && 5705 VT == Op.getOperand(1).getValueType() && 5706 "Unexpected SRA!"); 5707 5708 // Expand into a bunch of logical ops, followed by a select_cc. 5709 SDValue Lo = Op.getOperand(0); 5710 SDValue Hi = Op.getOperand(1); 5711 SDValue Amt = Op.getOperand(2); 5712 EVT AmtVT = Amt.getValueType(); 5713 5714 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 5715 DAG.getConstant(BitWidth, AmtVT), Amt); 5716 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 5717 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 5718 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 5719 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 5720 DAG.getConstant(-BitWidth, AmtVT)); 5721 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 5722 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 5723 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT), 5724 Tmp4, Tmp6, ISD::SETLE); 5725 SDValue OutOps[] = { OutLo, OutHi }; 5726 return DAG.getMergeValues(OutOps, dl); 5727 } 5728 5729 //===----------------------------------------------------------------------===// 5730 // Vector related lowering. 5731 // 5732 5733 /// BuildSplatI - Build a canonical splati of Val with an element size of 5734 /// SplatSize. Cast the result to VT. 5735 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 5736 SelectionDAG &DAG, SDLoc dl) { 5737 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 5738 5739 static const EVT VTys[] = { // canonical VT to use for each size. 5740 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 5741 }; 5742 5743 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 5744 5745 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 5746 if (Val == -1) 5747 SplatSize = 1; 5748 5749 EVT CanonicalVT = VTys[SplatSize-1]; 5750 5751 // Build a canonical splat for this value. 5752 SDValue Elt = DAG.getConstant(Val, MVT::i32); 5753 SmallVector<SDValue, 8> Ops; 5754 Ops.assign(CanonicalVT.getVectorNumElements(), Elt); 5755 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops); 5756 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res); 5757 } 5758 5759 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 5760 /// specified intrinsic ID. 5761 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, 5762 SelectionDAG &DAG, SDLoc dl, 5763 EVT DestVT = MVT::Other) { 5764 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 5765 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 5766 DAG.getConstant(IID, MVT::i32), Op); 5767 } 5768 5769 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 5770 /// specified intrinsic ID. 5771 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 5772 SelectionDAG &DAG, SDLoc dl, 5773 EVT DestVT = MVT::Other) { 5774 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 5775 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 5776 DAG.getConstant(IID, MVT::i32), LHS, RHS); 5777 } 5778 5779 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 5780 /// specified intrinsic ID. 5781 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 5782 SDValue Op2, SelectionDAG &DAG, 5783 SDLoc dl, EVT DestVT = MVT::Other) { 5784 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 5785 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 5786 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2); 5787 } 5788 5789 5790 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 5791 /// amount. The result has the specified value type. 5792 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, 5793 EVT VT, SelectionDAG &DAG, SDLoc dl) { 5794 // Force LHS/RHS to be the right type. 5795 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 5796 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 5797 5798 int Ops[16]; 5799 for (unsigned i = 0; i != 16; ++i) 5800 Ops[i] = i + Amt; 5801 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 5802 return DAG.getNode(ISD::BITCAST, dl, VT, T); 5803 } 5804 5805 // If this is a case we can't handle, return null and let the default 5806 // expansion code take care of it. If we CAN select this case, and if it 5807 // selects to a single instruction, return Op. Otherwise, if we can codegen 5808 // this case more efficiently than a constant pool load, lower it to the 5809 // sequence of ops that should be used. 5810 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 5811 SelectionDAG &DAG) const { 5812 SDLoc dl(Op); 5813 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 5814 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 5815 5816 // Check if this is a splat of a constant value. 5817 APInt APSplatBits, APSplatUndef; 5818 unsigned SplatBitSize; 5819 bool HasAnyUndefs; 5820 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 5821 HasAnyUndefs, 0, true) || SplatBitSize > 32) 5822 return SDValue(); 5823 5824 unsigned SplatBits = APSplatBits.getZExtValue(); 5825 unsigned SplatUndef = APSplatUndef.getZExtValue(); 5826 unsigned SplatSize = SplatBitSize / 8; 5827 5828 // First, handle single instruction cases. 5829 5830 // All zeros? 5831 if (SplatBits == 0) { 5832 // Canonicalize all zero vectors to be v4i32. 5833 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 5834 SDValue Z = DAG.getConstant(0, MVT::i32); 5835 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z); 5836 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 5837 } 5838 return Op; 5839 } 5840 5841 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 5842 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 5843 (32-SplatBitSize)); 5844 if (SextVal >= -16 && SextVal <= 15) 5845 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 5846 5847 5848 // Two instruction sequences. 5849 5850 // If this value is in the range [-32,30] and is even, use: 5851 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 5852 // If this value is in the range [17,31] and is odd, use: 5853 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 5854 // If this value is in the range [-31,-17] and is odd, use: 5855 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 5856 // Note the last two are three-instruction sequences. 5857 if (SextVal >= -32 && SextVal <= 31) { 5858 // To avoid having these optimizations undone by constant folding, 5859 // we convert to a pseudo that will be expanded later into one of 5860 // the above forms. 5861 SDValue Elt = DAG.getConstant(SextVal, MVT::i32); 5862 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 5863 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 5864 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32); 5865 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 5866 if (VT == Op.getValueType()) 5867 return RetVal; 5868 else 5869 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 5870 } 5871 5872 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 5873 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 5874 // for fneg/fabs. 5875 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 5876 // Make -1 and vspltisw -1: 5877 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 5878 5879 // Make the VSLW intrinsic, computing 0x8000_0000. 5880 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 5881 OnesV, DAG, dl); 5882 5883 // xor by OnesV to invert it. 5884 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 5885 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 5886 } 5887 5888 // The remaining cases assume either big endian element order or 5889 // a splat-size that equates to the element size of the vector 5890 // to be built. An example that doesn't work for little endian is 5891 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits 5892 // and a vector element size of 16 bits. The code below will 5893 // produce the vector in big endian element order, which for little 5894 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}. 5895 5896 // For now, just avoid these optimizations in that case. 5897 // FIXME: Develop correct optimizations for LE with mismatched 5898 // splat and element sizes. 5899 5900 if (Subtarget.isLittleEndian() && 5901 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits()) 5902 return SDValue(); 5903 5904 // Check to see if this is a wide variety of vsplti*, binop self cases. 5905 static const signed char SplatCsts[] = { 5906 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 5907 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 5908 }; 5909 5910 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 5911 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 5912 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 5913 int i = SplatCsts[idx]; 5914 5915 // Figure out what shift amount will be used by altivec if shifted by i in 5916 // this splat size. 5917 unsigned TypeShiftAmt = i & (SplatBitSize-1); 5918 5919 // vsplti + shl self. 5920 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 5921 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 5922 static const unsigned IIDs[] = { // Intrinsic to use for each size. 5923 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 5924 Intrinsic::ppc_altivec_vslw 5925 }; 5926 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 5927 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 5928 } 5929 5930 // vsplti + srl self. 5931 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 5932 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 5933 static const unsigned IIDs[] = { // Intrinsic to use for each size. 5934 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 5935 Intrinsic::ppc_altivec_vsrw 5936 }; 5937 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 5938 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 5939 } 5940 5941 // vsplti + sra self. 5942 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 5943 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 5944 static const unsigned IIDs[] = { // Intrinsic to use for each size. 5945 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 5946 Intrinsic::ppc_altivec_vsraw 5947 }; 5948 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 5949 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 5950 } 5951 5952 // vsplti + rol self. 5953 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 5954 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 5955 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 5956 static const unsigned IIDs[] = { // Intrinsic to use for each size. 5957 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 5958 Intrinsic::ppc_altivec_vrlw 5959 }; 5960 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 5961 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 5962 } 5963 5964 // t = vsplti c, result = vsldoi t, t, 1 5965 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 5966 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 5967 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl); 5968 } 5969 // t = vsplti c, result = vsldoi t, t, 2 5970 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 5971 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 5972 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl); 5973 } 5974 // t = vsplti c, result = vsldoi t, t, 3 5975 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 5976 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 5977 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl); 5978 } 5979 } 5980 5981 return SDValue(); 5982 } 5983 5984 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5985 /// the specified operations to build the shuffle. 5986 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5987 SDValue RHS, SelectionDAG &DAG, 5988 SDLoc dl) { 5989 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5990 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5991 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5992 5993 enum { 5994 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5995 OP_VMRGHW, 5996 OP_VMRGLW, 5997 OP_VSPLTISW0, 5998 OP_VSPLTISW1, 5999 OP_VSPLTISW2, 6000 OP_VSPLTISW3, 6001 OP_VSLDOI4, 6002 OP_VSLDOI8, 6003 OP_VSLDOI12 6004 }; 6005 6006 if (OpNum == OP_COPY) { 6007 if (LHSID == (1*9+2)*9+3) return LHS; 6008 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6009 return RHS; 6010 } 6011 6012 SDValue OpLHS, OpRHS; 6013 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6014 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6015 6016 int ShufIdxs[16]; 6017 switch (OpNum) { 6018 default: llvm_unreachable("Unknown i32 permute!"); 6019 case OP_VMRGHW: 6020 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 6021 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 6022 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 6023 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 6024 break; 6025 case OP_VMRGLW: 6026 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 6027 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 6028 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 6029 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 6030 break; 6031 case OP_VSPLTISW0: 6032 for (unsigned i = 0; i != 16; ++i) 6033 ShufIdxs[i] = (i&3)+0; 6034 break; 6035 case OP_VSPLTISW1: 6036 for (unsigned i = 0; i != 16; ++i) 6037 ShufIdxs[i] = (i&3)+4; 6038 break; 6039 case OP_VSPLTISW2: 6040 for (unsigned i = 0; i != 16; ++i) 6041 ShufIdxs[i] = (i&3)+8; 6042 break; 6043 case OP_VSPLTISW3: 6044 for (unsigned i = 0; i != 16; ++i) 6045 ShufIdxs[i] = (i&3)+12; 6046 break; 6047 case OP_VSLDOI4: 6048 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 6049 case OP_VSLDOI8: 6050 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 6051 case OP_VSLDOI12: 6052 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 6053 } 6054 EVT VT = OpLHS.getValueType(); 6055 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 6056 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 6057 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 6058 return DAG.getNode(ISD::BITCAST, dl, VT, T); 6059 } 6060 6061 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 6062 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 6063 /// return the code it can be lowered into. Worst case, it can always be 6064 /// lowered into a vperm. 6065 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 6066 SelectionDAG &DAG) const { 6067 SDLoc dl(Op); 6068 SDValue V1 = Op.getOperand(0); 6069 SDValue V2 = Op.getOperand(1); 6070 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6071 EVT VT = Op.getValueType(); 6072 bool isLittleEndian = Subtarget.isLittleEndian(); 6073 6074 // Cases that are handled by instructions that take permute immediates 6075 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 6076 // selected by the instruction selector. 6077 if (V2.getOpcode() == ISD::UNDEF) { 6078 if (PPC::isSplatShuffleMask(SVOp, 1) || 6079 PPC::isSplatShuffleMask(SVOp, 2) || 6080 PPC::isSplatShuffleMask(SVOp, 4) || 6081 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 6082 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 6083 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 6084 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 6085 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 6086 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 6087 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 6088 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 6089 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) { 6090 return Op; 6091 } 6092 } 6093 6094 // Altivec has a variety of "shuffle immediates" that take two vector inputs 6095 // and produce a fixed permutation. If any of these match, do not lower to 6096 // VPERM. 6097 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 6098 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 6099 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 6100 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 6101 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 6102 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 6103 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 6104 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 6105 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 6106 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG)) 6107 return Op; 6108 6109 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 6110 // perfect shuffle table to emit an optimal matching sequence. 6111 ArrayRef<int> PermMask = SVOp->getMask(); 6112 6113 unsigned PFIndexes[4]; 6114 bool isFourElementShuffle = true; 6115 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 6116 unsigned EltNo = 8; // Start out undef. 6117 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 6118 if (PermMask[i*4+j] < 0) 6119 continue; // Undef, ignore it. 6120 6121 unsigned ByteSource = PermMask[i*4+j]; 6122 if ((ByteSource & 3) != j) { 6123 isFourElementShuffle = false; 6124 break; 6125 } 6126 6127 if (EltNo == 8) { 6128 EltNo = ByteSource/4; 6129 } else if (EltNo != ByteSource/4) { 6130 isFourElementShuffle = false; 6131 break; 6132 } 6133 } 6134 PFIndexes[i] = EltNo; 6135 } 6136 6137 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 6138 // perfect shuffle vector to determine if it is cost effective to do this as 6139 // discrete instructions, or whether we should use a vperm. 6140 // For now, we skip this for little endian until such time as we have a 6141 // little-endian perfect shuffle table. 6142 if (isFourElementShuffle && !isLittleEndian) { 6143 // Compute the index in the perfect shuffle table. 6144 unsigned PFTableIndex = 6145 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6146 6147 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6148 unsigned Cost = (PFEntry >> 30); 6149 6150 // Determining when to avoid vperm is tricky. Many things affect the cost 6151 // of vperm, particularly how many times the perm mask needs to be computed. 6152 // For example, if the perm mask can be hoisted out of a loop or is already 6153 // used (perhaps because there are multiple permutes with the same shuffle 6154 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 6155 // the loop requires an extra register. 6156 // 6157 // As a compromise, we only emit discrete instructions if the shuffle can be 6158 // generated in 3 or fewer operations. When we have loop information 6159 // available, if this block is within a loop, we should avoid using vperm 6160 // for 3-operation perms and use a constant pool load instead. 6161 if (Cost < 3) 6162 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6163 } 6164 6165 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 6166 // vector that will get spilled to the constant pool. 6167 if (V2.getOpcode() == ISD::UNDEF) V2 = V1; 6168 6169 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 6170 // that it is in input element units, not in bytes. Convert now. 6171 6172 // For little endian, the order of the input vectors is reversed, and 6173 // the permutation mask is complemented with respect to 31. This is 6174 // necessary to produce proper semantics with the big-endian-biased vperm 6175 // instruction. 6176 EVT EltVT = V1.getValueType().getVectorElementType(); 6177 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 6178 6179 SmallVector<SDValue, 16> ResultMask; 6180 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6181 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 6182 6183 for (unsigned j = 0; j != BytesPerElement; ++j) 6184 if (isLittleEndian) 6185 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j), 6186 MVT::i32)); 6187 else 6188 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j, 6189 MVT::i32)); 6190 } 6191 6192 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8, 6193 ResultMask); 6194 if (isLittleEndian) 6195 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 6196 V2, V1, VPermMask); 6197 else 6198 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 6199 V1, V2, VPermMask); 6200 } 6201 6202 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an 6203 /// altivec comparison. If it is, return true and fill in Opc/isDot with 6204 /// information about the intrinsic. 6205 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc, 6206 bool &isDot) { 6207 unsigned IntrinsicID = 6208 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 6209 CompareOpc = -1; 6210 isDot = false; 6211 switch (IntrinsicID) { 6212 default: return false; 6213 // Comparison predicates. 6214 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break; 6215 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break; 6216 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break; 6217 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break; 6218 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break; 6219 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break; 6220 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break; 6221 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break; 6222 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break; 6223 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break; 6224 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break; 6225 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break; 6226 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break; 6227 6228 // Normal Comparisons. 6229 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break; 6230 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break; 6231 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break; 6232 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break; 6233 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break; 6234 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break; 6235 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break; 6236 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break; 6237 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break; 6238 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break; 6239 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break; 6240 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break; 6241 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break; 6242 } 6243 return true; 6244 } 6245 6246 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 6247 /// lower, do it, otherwise return null. 6248 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6249 SelectionDAG &DAG) const { 6250 // If this is a lowered altivec predicate compare, CompareOpc is set to the 6251 // opcode number of the comparison. 6252 SDLoc dl(Op); 6253 int CompareOpc; 6254 bool isDot; 6255 if (!getAltivecCompareInfo(Op, CompareOpc, isDot)) 6256 return SDValue(); // Don't custom lower most intrinsics. 6257 6258 // If this is a non-dot comparison, make the VCMP node and we are done. 6259 if (!isDot) { 6260 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 6261 Op.getOperand(1), Op.getOperand(2), 6262 DAG.getConstant(CompareOpc, MVT::i32)); 6263 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 6264 } 6265 6266 // Create the PPCISD altivec 'dot' comparison node. 6267 SDValue Ops[] = { 6268 Op.getOperand(2), // LHS 6269 Op.getOperand(3), // RHS 6270 DAG.getConstant(CompareOpc, MVT::i32) 6271 }; 6272 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 6273 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 6274 6275 // Now that we have the comparison, emit a copy from the CR to a GPR. 6276 // This is flagged to the above dot comparison. 6277 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 6278 DAG.getRegister(PPC::CR6, MVT::i32), 6279 CompNode.getValue(1)); 6280 6281 // Unpack the result based on how the target uses it. 6282 unsigned BitNo; // Bit # of CR6. 6283 bool InvertBit; // Invert result? 6284 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 6285 default: // Can't happen, don't crash on invalid number though. 6286 case 0: // Return the value of the EQ bit of CR6. 6287 BitNo = 0; InvertBit = false; 6288 break; 6289 case 1: // Return the inverted value of the EQ bit of CR6. 6290 BitNo = 0; InvertBit = true; 6291 break; 6292 case 2: // Return the value of the LT bit of CR6. 6293 BitNo = 2; InvertBit = false; 6294 break; 6295 case 3: // Return the inverted value of the LT bit of CR6. 6296 BitNo = 2; InvertBit = true; 6297 break; 6298 } 6299 6300 // Shift the bit into the low position. 6301 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 6302 DAG.getConstant(8-(3-BitNo), MVT::i32)); 6303 // Isolate the bit. 6304 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 6305 DAG.getConstant(1, MVT::i32)); 6306 6307 // If we are supposed to, toggle the bit. 6308 if (InvertBit) 6309 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 6310 DAG.getConstant(1, MVT::i32)); 6311 return Flags; 6312 } 6313 6314 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 6315 SelectionDAG &DAG) const { 6316 SDLoc dl(Op); 6317 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int 6318 // instructions), but for smaller types, we need to first extend up to v2i32 6319 // before doing going farther. 6320 if (Op.getValueType() == MVT::v2i64) { 6321 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 6322 if (ExtVT != MVT::v2i32) { 6323 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); 6324 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, 6325 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), 6326 ExtVT.getVectorElementType(), 4))); 6327 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); 6328 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, 6329 DAG.getValueType(MVT::v2i32)); 6330 } 6331 6332 return Op; 6333 } 6334 6335 return SDValue(); 6336 } 6337 6338 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 6339 SelectionDAG &DAG) const { 6340 SDLoc dl(Op); 6341 // Create a stack slot that is 16-byte aligned. 6342 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6343 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); 6344 EVT PtrVT = getPointerTy(); 6345 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6346 6347 // Store the input value into Value#0 of the stack slot. 6348 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, 6349 Op.getOperand(0), FIdx, MachinePointerInfo(), 6350 false, false, 0); 6351 // Load it out. 6352 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(), 6353 false, false, false, 0); 6354 } 6355 6356 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 6357 SDLoc dl(Op); 6358 if (Op.getValueType() == MVT::v4i32) { 6359 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6360 6361 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 6362 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 6363 6364 SDValue RHSSwap = // = vrlw RHS, 16 6365 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 6366 6367 // Shrinkify inputs to v8i16. 6368 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 6369 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 6370 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 6371 6372 // Low parts multiplied together, generating 32-bit results (we ignore the 6373 // top parts). 6374 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 6375 LHS, RHS, DAG, dl, MVT::v4i32); 6376 6377 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 6378 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 6379 // Shift the high parts up 16 bits. 6380 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 6381 Neg16, DAG, dl); 6382 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 6383 } else if (Op.getValueType() == MVT::v8i16) { 6384 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6385 6386 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 6387 6388 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 6389 LHS, RHS, Zero, DAG, dl); 6390 } else if (Op.getValueType() == MVT::v16i8) { 6391 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6392 bool isLittleEndian = Subtarget.isLittleEndian(); 6393 6394 // Multiply the even 8-bit parts, producing 16-bit sums. 6395 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 6396 LHS, RHS, DAG, dl, MVT::v8i16); 6397 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 6398 6399 // Multiply the odd 8-bit parts, producing 16-bit sums. 6400 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 6401 LHS, RHS, DAG, dl, MVT::v8i16); 6402 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 6403 6404 // Merge the results together. Because vmuleub and vmuloub are 6405 // instructions with a big-endian bias, we must reverse the 6406 // element numbering and reverse the meaning of "odd" and "even" 6407 // when generating little endian code. 6408 int Ops[16]; 6409 for (unsigned i = 0; i != 8; ++i) { 6410 if (isLittleEndian) { 6411 Ops[i*2 ] = 2*i; 6412 Ops[i*2+1] = 2*i+16; 6413 } else { 6414 Ops[i*2 ] = 2*i+1; 6415 Ops[i*2+1] = 2*i+1+16; 6416 } 6417 } 6418 if (isLittleEndian) 6419 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 6420 else 6421 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 6422 } else { 6423 llvm_unreachable("Unknown mul to lower!"); 6424 } 6425 } 6426 6427 /// LowerOperation - Provide custom lowering hooks for some operations. 6428 /// 6429 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6430 switch (Op.getOpcode()) { 6431 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 6432 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 6433 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 6434 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 6435 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 6436 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 6437 case ISD::SETCC: return LowerSETCC(Op, DAG); 6438 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 6439 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 6440 case ISD::VASTART: 6441 return LowerVASTART(Op, DAG, Subtarget); 6442 6443 case ISD::VAARG: 6444 return LowerVAARG(Op, DAG, Subtarget); 6445 6446 case ISD::VACOPY: 6447 return LowerVACOPY(Op, DAG, Subtarget); 6448 6449 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget); 6450 case ISD::DYNAMIC_STACKALLOC: 6451 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget); 6452 6453 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 6454 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 6455 6456 case ISD::LOAD: return LowerLOAD(Op, DAG); 6457 case ISD::STORE: return LowerSTORE(Op, DAG); 6458 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 6459 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 6460 case ISD::FP_TO_UINT: 6461 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 6462 SDLoc(Op)); 6463 case ISD::UINT_TO_FP: 6464 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 6465 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 6466 6467 // Lower 64-bit shifts. 6468 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 6469 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 6470 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 6471 6472 // Vector-related lowering. 6473 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 6474 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 6475 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 6476 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 6477 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); 6478 case ISD::MUL: return LowerMUL(Op, DAG); 6479 6480 // For counter-based loop handling. 6481 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 6482 6483 // Frame & Return address. 6484 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 6485 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 6486 } 6487 } 6488 6489 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 6490 SmallVectorImpl<SDValue>&Results, 6491 SelectionDAG &DAG) const { 6492 const TargetMachine &TM = getTargetMachine(); 6493 SDLoc dl(N); 6494 switch (N->getOpcode()) { 6495 default: 6496 llvm_unreachable("Do not know how to custom type legalize this operation!"); 6497 case ISD::INTRINSIC_W_CHAIN: { 6498 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 6499 Intrinsic::ppc_is_decremented_ctr_nonzero) 6500 break; 6501 6502 assert(N->getValueType(0) == MVT::i1 && 6503 "Unexpected result type for CTR decrement intrinsic"); 6504 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0)); 6505 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 6506 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 6507 N->getOperand(1)); 6508 6509 Results.push_back(NewInt); 6510 Results.push_back(NewInt.getValue(1)); 6511 break; 6512 } 6513 case ISD::VAARG: { 6514 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI() 6515 || TM.getSubtarget<PPCSubtarget>().isPPC64()) 6516 return; 6517 6518 EVT VT = N->getValueType(0); 6519 6520 if (VT == MVT::i64) { 6521 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget); 6522 6523 Results.push_back(NewNode); 6524 Results.push_back(NewNode.getValue(1)); 6525 } 6526 return; 6527 } 6528 case ISD::FP_ROUND_INREG: { 6529 assert(N->getValueType(0) == MVT::ppcf128); 6530 assert(N->getOperand(0).getValueType() == MVT::ppcf128); 6531 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 6532 MVT::f64, N->getOperand(0), 6533 DAG.getIntPtrConstant(0)); 6534 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 6535 MVT::f64, N->getOperand(0), 6536 DAG.getIntPtrConstant(1)); 6537 6538 // Add the two halves of the long double in round-to-zero mode. 6539 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 6540 6541 // We know the low half is about to be thrown away, so just use something 6542 // convenient. 6543 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 6544 FPreg, FPreg)); 6545 return; 6546 } 6547 case ISD::FP_TO_SINT: 6548 // LowerFP_TO_INT() can only handle f32 and f64. 6549 if (N->getOperand(0).getValueType() == MVT::ppcf128) 6550 return; 6551 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 6552 return; 6553 } 6554 } 6555 6556 6557 //===----------------------------------------------------------------------===// 6558 // Other Lowering Code 6559 //===----------------------------------------------------------------------===// 6560 6561 MachineBasicBlock * 6562 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB, 6563 bool is64bit, unsigned BinOpcode) const { 6564 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 6565 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6566 6567 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 6568 MachineFunction *F = BB->getParent(); 6569 MachineFunction::iterator It = BB; 6570 ++It; 6571 6572 unsigned dest = MI->getOperand(0).getReg(); 6573 unsigned ptrA = MI->getOperand(1).getReg(); 6574 unsigned ptrB = MI->getOperand(2).getReg(); 6575 unsigned incr = MI->getOperand(3).getReg(); 6576 DebugLoc dl = MI->getDebugLoc(); 6577 6578 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 6579 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 6580 F->insert(It, loopMBB); 6581 F->insert(It, exitMBB); 6582 exitMBB->splice(exitMBB->begin(), BB, 6583 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 6584 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 6585 6586 MachineRegisterInfo &RegInfo = F->getRegInfo(); 6587 unsigned TmpReg = (!BinOpcode) ? incr : 6588 RegInfo.createVirtualRegister( 6589 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass : 6590 (const TargetRegisterClass *) &PPC::GPRCRegClass); 6591 6592 // thisMBB: 6593 // ... 6594 // fallthrough --> loopMBB 6595 BB->addSuccessor(loopMBB); 6596 6597 // loopMBB: 6598 // l[wd]arx dest, ptr 6599 // add r0, dest, incr 6600 // st[wd]cx. r0, ptr 6601 // bne- loopMBB 6602 // fallthrough --> exitMBB 6603 BB = loopMBB; 6604 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest) 6605 .addReg(ptrA).addReg(ptrB); 6606 if (BinOpcode) 6607 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 6608 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 6609 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 6610 BuildMI(BB, dl, TII->get(PPC::BCC)) 6611 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 6612 BB->addSuccessor(loopMBB); 6613 BB->addSuccessor(exitMBB); 6614 6615 // exitMBB: 6616 // ... 6617 BB = exitMBB; 6618 return BB; 6619 } 6620 6621 MachineBasicBlock * 6622 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI, 6623 MachineBasicBlock *BB, 6624 bool is8bit, // operation 6625 unsigned BinOpcode) const { 6626 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 6627 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6628 // In 64 bit mode we have to use 64 bits for addresses, even though the 6629 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 6630 // registers without caring whether they're 32 or 64, but here we're 6631 // doing actual arithmetic on the addresses. 6632 bool is64bit = Subtarget.isPPC64(); 6633 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 6634 6635 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 6636 MachineFunction *F = BB->getParent(); 6637 MachineFunction::iterator It = BB; 6638 ++It; 6639 6640 unsigned dest = MI->getOperand(0).getReg(); 6641 unsigned ptrA = MI->getOperand(1).getReg(); 6642 unsigned ptrB = MI->getOperand(2).getReg(); 6643 unsigned incr = MI->getOperand(3).getReg(); 6644 DebugLoc dl = MI->getDebugLoc(); 6645 6646 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 6647 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 6648 F->insert(It, loopMBB); 6649 F->insert(It, exitMBB); 6650 exitMBB->splice(exitMBB->begin(), BB, 6651 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 6652 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 6653 6654 MachineRegisterInfo &RegInfo = F->getRegInfo(); 6655 const TargetRegisterClass *RC = 6656 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass : 6657 (const TargetRegisterClass *) &PPC::GPRCRegClass; 6658 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 6659 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 6660 unsigned ShiftReg = RegInfo.createVirtualRegister(RC); 6661 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 6662 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 6663 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 6664 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 6665 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 6666 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 6667 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 6668 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 6669 unsigned Ptr1Reg; 6670 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 6671 6672 // thisMBB: 6673 // ... 6674 // fallthrough --> loopMBB 6675 BB->addSuccessor(loopMBB); 6676 6677 // The 4-byte load must be aligned, while a char or short may be 6678 // anywhere in the word. Hence all this nasty bookkeeping code. 6679 // add ptr1, ptrA, ptrB [copy if ptrA==0] 6680 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 6681 // xori shift, shift1, 24 [16] 6682 // rlwinm ptr, ptr1, 0, 0, 29 6683 // slw incr2, incr, shift 6684 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 6685 // slw mask, mask2, shift 6686 // loopMBB: 6687 // lwarx tmpDest, ptr 6688 // add tmp, tmpDest, incr2 6689 // andc tmp2, tmpDest, mask 6690 // and tmp3, tmp, mask 6691 // or tmp4, tmp3, tmp2 6692 // stwcx. tmp4, ptr 6693 // bne- loopMBB 6694 // fallthrough --> exitMBB 6695 // srw dest, tmpDest, shift 6696 if (ptrA != ZeroReg) { 6697 Ptr1Reg = RegInfo.createVirtualRegister(RC); 6698 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 6699 .addReg(ptrA).addReg(ptrB); 6700 } else { 6701 Ptr1Reg = ptrB; 6702 } 6703 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 6704 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 6705 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 6706 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 6707 if (is64bit) 6708 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 6709 .addReg(Ptr1Reg).addImm(0).addImm(61); 6710 else 6711 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 6712 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 6713 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 6714 .addReg(incr).addReg(ShiftReg); 6715 if (is8bit) 6716 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 6717 else { 6718 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 6719 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 6720 } 6721 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 6722 .addReg(Mask2Reg).addReg(ShiftReg); 6723 6724 BB = loopMBB; 6725 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 6726 .addReg(ZeroReg).addReg(PtrReg); 6727 if (BinOpcode) 6728 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 6729 .addReg(Incr2Reg).addReg(TmpDestReg); 6730 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 6731 .addReg(TmpDestReg).addReg(MaskReg); 6732 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 6733 .addReg(TmpReg).addReg(MaskReg); 6734 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 6735 .addReg(Tmp3Reg).addReg(Tmp2Reg); 6736 BuildMI(BB, dl, TII->get(PPC::STWCX)) 6737 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 6738 BuildMI(BB, dl, TII->get(PPC::BCC)) 6739 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 6740 BB->addSuccessor(loopMBB); 6741 BB->addSuccessor(exitMBB); 6742 6743 // exitMBB: 6744 // ... 6745 BB = exitMBB; 6746 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 6747 .addReg(ShiftReg); 6748 return BB; 6749 } 6750 6751 llvm::MachineBasicBlock* 6752 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI, 6753 MachineBasicBlock *MBB) const { 6754 DebugLoc DL = MI->getDebugLoc(); 6755 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6756 6757 MachineFunction *MF = MBB->getParent(); 6758 MachineRegisterInfo &MRI = MF->getRegInfo(); 6759 6760 const BasicBlock *BB = MBB->getBasicBlock(); 6761 MachineFunction::iterator I = MBB; 6762 ++I; 6763 6764 // Memory Reference 6765 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 6766 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 6767 6768 unsigned DstReg = MI->getOperand(0).getReg(); 6769 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 6770 assert(RC->hasType(MVT::i32) && "Invalid destination!"); 6771 unsigned mainDstReg = MRI.createVirtualRegister(RC); 6772 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 6773 6774 MVT PVT = getPointerTy(); 6775 assert((PVT == MVT::i64 || PVT == MVT::i32) && 6776 "Invalid Pointer Size!"); 6777 // For v = setjmp(buf), we generate 6778 // 6779 // thisMBB: 6780 // SjLjSetup mainMBB 6781 // bl mainMBB 6782 // v_restore = 1 6783 // b sinkMBB 6784 // 6785 // mainMBB: 6786 // buf[LabelOffset] = LR 6787 // v_main = 0 6788 // 6789 // sinkMBB: 6790 // v = phi(main, restore) 6791 // 6792 6793 MachineBasicBlock *thisMBB = MBB; 6794 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 6795 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 6796 MF->insert(I, mainMBB); 6797 MF->insert(I, sinkMBB); 6798 6799 MachineInstrBuilder MIB; 6800 6801 // Transfer the remainder of BB and its successor edges to sinkMBB. 6802 sinkMBB->splice(sinkMBB->begin(), MBB, 6803 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 6804 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 6805 6806 // Note that the structure of the jmp_buf used here is not compatible 6807 // with that used by libc, and is not designed to be. Specifically, it 6808 // stores only those 'reserved' registers that LLVM does not otherwise 6809 // understand how to spill. Also, by convention, by the time this 6810 // intrinsic is called, Clang has already stored the frame address in the 6811 // first slot of the buffer and stack address in the third. Following the 6812 // X86 target code, we'll store the jump address in the second slot. We also 6813 // need to save the TOC pointer (R2) to handle jumps between shared 6814 // libraries, and that will be stored in the fourth slot. The thread 6815 // identifier (R13) is not affected. 6816 6817 // thisMBB: 6818 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 6819 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 6820 const int64_t BPOffset = 4 * PVT.getStoreSize(); 6821 6822 // Prepare IP either in reg. 6823 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 6824 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 6825 unsigned BufReg = MI->getOperand(1).getReg(); 6826 6827 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 6828 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 6829 .addReg(PPC::X2) 6830 .addImm(TOCOffset) 6831 .addReg(BufReg); 6832 MIB.setMemRefs(MMOBegin, MMOEnd); 6833 } 6834 6835 // Naked functions never have a base pointer, and so we use r1. For all 6836 // other functions, this decision must be delayed until during PEI. 6837 unsigned BaseReg; 6838 if (MF->getFunction()->getAttributes().hasAttribute( 6839 AttributeSet::FunctionIndex, Attribute::Naked)) 6840 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 6841 else 6842 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 6843 6844 MIB = BuildMI(*thisMBB, MI, DL, 6845 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 6846 .addReg(BaseReg) 6847 .addImm(BPOffset) 6848 .addReg(BufReg); 6849 MIB.setMemRefs(MMOBegin, MMOEnd); 6850 6851 // Setup 6852 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 6853 const PPCRegisterInfo *TRI = 6854 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo()); 6855 MIB.addRegMask(TRI->getNoPreservedMask()); 6856 6857 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 6858 6859 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 6860 .addMBB(mainMBB); 6861 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 6862 6863 thisMBB->addSuccessor(mainMBB, /* weight */ 0); 6864 thisMBB->addSuccessor(sinkMBB, /* weight */ 1); 6865 6866 // mainMBB: 6867 // mainDstReg = 0 6868 MIB = BuildMI(mainMBB, DL, 6869 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 6870 6871 // Store IP 6872 if (Subtarget.isPPC64()) { 6873 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 6874 .addReg(LabelReg) 6875 .addImm(LabelOffset) 6876 .addReg(BufReg); 6877 } else { 6878 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 6879 .addReg(LabelReg) 6880 .addImm(LabelOffset) 6881 .addReg(BufReg); 6882 } 6883 6884 MIB.setMemRefs(MMOBegin, MMOEnd); 6885 6886 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 6887 mainMBB->addSuccessor(sinkMBB); 6888 6889 // sinkMBB: 6890 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 6891 TII->get(PPC::PHI), DstReg) 6892 .addReg(mainDstReg).addMBB(mainMBB) 6893 .addReg(restoreDstReg).addMBB(thisMBB); 6894 6895 MI->eraseFromParent(); 6896 return sinkMBB; 6897 } 6898 6899 MachineBasicBlock * 6900 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI, 6901 MachineBasicBlock *MBB) const { 6902 DebugLoc DL = MI->getDebugLoc(); 6903 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6904 6905 MachineFunction *MF = MBB->getParent(); 6906 MachineRegisterInfo &MRI = MF->getRegInfo(); 6907 6908 // Memory Reference 6909 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 6910 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 6911 6912 MVT PVT = getPointerTy(); 6913 assert((PVT == MVT::i64 || PVT == MVT::i32) && 6914 "Invalid Pointer Size!"); 6915 6916 const TargetRegisterClass *RC = 6917 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6918 unsigned Tmp = MRI.createVirtualRegister(RC); 6919 // Since FP is only updated here but NOT referenced, it's treated as GPR. 6920 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 6921 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 6922 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : 6923 (Subtarget.isSVR4ABI() && 6924 MF->getTarget().getRelocationModel() == Reloc::PIC_ ? 6925 PPC::R29 : PPC::R30); 6926 6927 MachineInstrBuilder MIB; 6928 6929 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 6930 const int64_t SPOffset = 2 * PVT.getStoreSize(); 6931 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 6932 const int64_t BPOffset = 4 * PVT.getStoreSize(); 6933 6934 unsigned BufReg = MI->getOperand(0).getReg(); 6935 6936 // Reload FP (the jumped-to function may not have had a 6937 // frame pointer, and if so, then its r31 will be restored 6938 // as necessary). 6939 if (PVT == MVT::i64) { 6940 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 6941 .addImm(0) 6942 .addReg(BufReg); 6943 } else { 6944 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 6945 .addImm(0) 6946 .addReg(BufReg); 6947 } 6948 MIB.setMemRefs(MMOBegin, MMOEnd); 6949 6950 // Reload IP 6951 if (PVT == MVT::i64) { 6952 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 6953 .addImm(LabelOffset) 6954 .addReg(BufReg); 6955 } else { 6956 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 6957 .addImm(LabelOffset) 6958 .addReg(BufReg); 6959 } 6960 MIB.setMemRefs(MMOBegin, MMOEnd); 6961 6962 // Reload SP 6963 if (PVT == MVT::i64) { 6964 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 6965 .addImm(SPOffset) 6966 .addReg(BufReg); 6967 } else { 6968 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 6969 .addImm(SPOffset) 6970 .addReg(BufReg); 6971 } 6972 MIB.setMemRefs(MMOBegin, MMOEnd); 6973 6974 // Reload BP 6975 if (PVT == MVT::i64) { 6976 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 6977 .addImm(BPOffset) 6978 .addReg(BufReg); 6979 } else { 6980 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 6981 .addImm(BPOffset) 6982 .addReg(BufReg); 6983 } 6984 MIB.setMemRefs(MMOBegin, MMOEnd); 6985 6986 // Reload TOC 6987 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 6988 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 6989 .addImm(TOCOffset) 6990 .addReg(BufReg); 6991 6992 MIB.setMemRefs(MMOBegin, MMOEnd); 6993 } 6994 6995 // Jump 6996 BuildMI(*MBB, MI, DL, 6997 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 6998 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 6999 7000 MI->eraseFromParent(); 7001 return MBB; 7002 } 7003 7004 MachineBasicBlock * 7005 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 7006 MachineBasicBlock *BB) const { 7007 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 || 7008 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) { 7009 return emitEHSjLjSetJmp(MI, BB); 7010 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 || 7011 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) { 7012 return emitEHSjLjLongJmp(MI, BB); 7013 } 7014 7015 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 7016 7017 // To "insert" these instructions we actually have to insert their 7018 // control-flow patterns. 7019 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7020 MachineFunction::iterator It = BB; 7021 ++It; 7022 7023 MachineFunction *F = BB->getParent(); 7024 7025 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 || 7026 MI->getOpcode() == PPC::SELECT_CC_I8 || 7027 MI->getOpcode() == PPC::SELECT_I4 || 7028 MI->getOpcode() == PPC::SELECT_I8)) { 7029 SmallVector<MachineOperand, 2> Cond; 7030 if (MI->getOpcode() == PPC::SELECT_CC_I4 || 7031 MI->getOpcode() == PPC::SELECT_CC_I8) 7032 Cond.push_back(MI->getOperand(4)); 7033 else 7034 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 7035 Cond.push_back(MI->getOperand(1)); 7036 7037 DebugLoc dl = MI->getDebugLoc(); 7038 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 7039 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(), 7040 Cond, MI->getOperand(2).getReg(), 7041 MI->getOperand(3).getReg()); 7042 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 || 7043 MI->getOpcode() == PPC::SELECT_CC_I8 || 7044 MI->getOpcode() == PPC::SELECT_CC_F4 || 7045 MI->getOpcode() == PPC::SELECT_CC_F8 || 7046 MI->getOpcode() == PPC::SELECT_CC_VRRC || 7047 MI->getOpcode() == PPC::SELECT_I4 || 7048 MI->getOpcode() == PPC::SELECT_I8 || 7049 MI->getOpcode() == PPC::SELECT_F4 || 7050 MI->getOpcode() == PPC::SELECT_F8 || 7051 MI->getOpcode() == PPC::SELECT_VRRC) { 7052 // The incoming instruction knows the destination vreg to set, the 7053 // condition code register to branch on, the true/false values to 7054 // select between, and a branch opcode to use. 7055 7056 // thisMBB: 7057 // ... 7058 // TrueVal = ... 7059 // cmpTY ccX, r1, r2 7060 // bCC copy1MBB 7061 // fallthrough --> copy0MBB 7062 MachineBasicBlock *thisMBB = BB; 7063 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 7064 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 7065 DebugLoc dl = MI->getDebugLoc(); 7066 F->insert(It, copy0MBB); 7067 F->insert(It, sinkMBB); 7068 7069 // Transfer the remainder of BB and its successor edges to sinkMBB. 7070 sinkMBB->splice(sinkMBB->begin(), BB, 7071 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7072 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 7073 7074 // Next, add the true and fallthrough blocks as its successors. 7075 BB->addSuccessor(copy0MBB); 7076 BB->addSuccessor(sinkMBB); 7077 7078 if (MI->getOpcode() == PPC::SELECT_I4 || 7079 MI->getOpcode() == PPC::SELECT_I8 || 7080 MI->getOpcode() == PPC::SELECT_F4 || 7081 MI->getOpcode() == PPC::SELECT_F8 || 7082 MI->getOpcode() == PPC::SELECT_VRRC) { 7083 BuildMI(BB, dl, TII->get(PPC::BC)) 7084 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB); 7085 } else { 7086 unsigned SelectPred = MI->getOperand(4).getImm(); 7087 BuildMI(BB, dl, TII->get(PPC::BCC)) 7088 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB); 7089 } 7090 7091 // copy0MBB: 7092 // %FalseValue = ... 7093 // # fallthrough to sinkMBB 7094 BB = copy0MBB; 7095 7096 // Update machine-CFG edges 7097 BB->addSuccessor(sinkMBB); 7098 7099 // sinkMBB: 7100 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 7101 // ... 7102 BB = sinkMBB; 7103 BuildMI(*BB, BB->begin(), dl, 7104 TII->get(PPC::PHI), MI->getOperand(0).getReg()) 7105 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB) 7106 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 7107 } 7108 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 7109 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 7110 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 7111 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 7112 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 7113 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4); 7114 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 7115 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8); 7116 7117 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 7118 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 7119 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 7120 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 7121 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 7122 BB = EmitAtomicBinary(MI, BB, false, PPC::AND); 7123 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 7124 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8); 7125 7126 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 7127 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 7128 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 7129 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 7130 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 7131 BB = EmitAtomicBinary(MI, BB, false, PPC::OR); 7132 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 7133 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8); 7134 7135 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 7136 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 7137 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 7138 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 7139 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 7140 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR); 7141 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 7142 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8); 7143 7144 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 7145 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 7146 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 7147 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 7148 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 7149 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND); 7150 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 7151 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8); 7152 7153 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 7154 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 7155 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 7156 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 7157 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 7158 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF); 7159 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 7160 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8); 7161 7162 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8) 7163 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 7164 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16) 7165 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 7166 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32) 7167 BB = EmitAtomicBinary(MI, BB, false, 0); 7168 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64) 7169 BB = EmitAtomicBinary(MI, BB, true, 0); 7170 7171 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 7172 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) { 7173 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 7174 7175 unsigned dest = MI->getOperand(0).getReg(); 7176 unsigned ptrA = MI->getOperand(1).getReg(); 7177 unsigned ptrB = MI->getOperand(2).getReg(); 7178 unsigned oldval = MI->getOperand(3).getReg(); 7179 unsigned newval = MI->getOperand(4).getReg(); 7180 DebugLoc dl = MI->getDebugLoc(); 7181 7182 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 7183 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 7184 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 7185 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 7186 F->insert(It, loop1MBB); 7187 F->insert(It, loop2MBB); 7188 F->insert(It, midMBB); 7189 F->insert(It, exitMBB); 7190 exitMBB->splice(exitMBB->begin(), BB, 7191 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7192 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7193 7194 // thisMBB: 7195 // ... 7196 // fallthrough --> loopMBB 7197 BB->addSuccessor(loop1MBB); 7198 7199 // loop1MBB: 7200 // l[wd]arx dest, ptr 7201 // cmp[wd] dest, oldval 7202 // bne- midMBB 7203 // loop2MBB: 7204 // st[wd]cx. newval, ptr 7205 // bne- loopMBB 7206 // b exitBB 7207 // midMBB: 7208 // st[wd]cx. dest, ptr 7209 // exitBB: 7210 BB = loop1MBB; 7211 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest) 7212 .addReg(ptrA).addReg(ptrB); 7213 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 7214 .addReg(oldval).addReg(dest); 7215 BuildMI(BB, dl, TII->get(PPC::BCC)) 7216 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 7217 BB->addSuccessor(loop2MBB); 7218 BB->addSuccessor(midMBB); 7219 7220 BB = loop2MBB; 7221 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 7222 .addReg(newval).addReg(ptrA).addReg(ptrB); 7223 BuildMI(BB, dl, TII->get(PPC::BCC)) 7224 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 7225 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 7226 BB->addSuccessor(loop1MBB); 7227 BB->addSuccessor(exitMBB); 7228 7229 BB = midMBB; 7230 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 7231 .addReg(dest).addReg(ptrA).addReg(ptrB); 7232 BB->addSuccessor(exitMBB); 7233 7234 // exitMBB: 7235 // ... 7236 BB = exitMBB; 7237 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 7238 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 7239 // We must use 64-bit registers for addresses when targeting 64-bit, 7240 // since we're actually doing arithmetic on them. Other registers 7241 // can be 32-bit. 7242 bool is64bit = Subtarget.isPPC64(); 7243 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 7244 7245 unsigned dest = MI->getOperand(0).getReg(); 7246 unsigned ptrA = MI->getOperand(1).getReg(); 7247 unsigned ptrB = MI->getOperand(2).getReg(); 7248 unsigned oldval = MI->getOperand(3).getReg(); 7249 unsigned newval = MI->getOperand(4).getReg(); 7250 DebugLoc dl = MI->getDebugLoc(); 7251 7252 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 7253 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 7254 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 7255 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 7256 F->insert(It, loop1MBB); 7257 F->insert(It, loop2MBB); 7258 F->insert(It, midMBB); 7259 F->insert(It, exitMBB); 7260 exitMBB->splice(exitMBB->begin(), BB, 7261 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7262 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7263 7264 MachineRegisterInfo &RegInfo = F->getRegInfo(); 7265 const TargetRegisterClass *RC = 7266 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass : 7267 (const TargetRegisterClass *) &PPC::GPRCRegClass; 7268 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 7269 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 7270 unsigned ShiftReg = RegInfo.createVirtualRegister(RC); 7271 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 7272 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 7273 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 7274 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 7275 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 7276 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 7277 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 7278 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 7279 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 7280 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 7281 unsigned Ptr1Reg; 7282 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 7283 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 7284 // thisMBB: 7285 // ... 7286 // fallthrough --> loopMBB 7287 BB->addSuccessor(loop1MBB); 7288 7289 // The 4-byte load must be aligned, while a char or short may be 7290 // anywhere in the word. Hence all this nasty bookkeeping code. 7291 // add ptr1, ptrA, ptrB [copy if ptrA==0] 7292 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 7293 // xori shift, shift1, 24 [16] 7294 // rlwinm ptr, ptr1, 0, 0, 29 7295 // slw newval2, newval, shift 7296 // slw oldval2, oldval,shift 7297 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 7298 // slw mask, mask2, shift 7299 // and newval3, newval2, mask 7300 // and oldval3, oldval2, mask 7301 // loop1MBB: 7302 // lwarx tmpDest, ptr 7303 // and tmp, tmpDest, mask 7304 // cmpw tmp, oldval3 7305 // bne- midMBB 7306 // loop2MBB: 7307 // andc tmp2, tmpDest, mask 7308 // or tmp4, tmp2, newval3 7309 // stwcx. tmp4, ptr 7310 // bne- loop1MBB 7311 // b exitBB 7312 // midMBB: 7313 // stwcx. tmpDest, ptr 7314 // exitBB: 7315 // srw dest, tmpDest, shift 7316 if (ptrA != ZeroReg) { 7317 Ptr1Reg = RegInfo.createVirtualRegister(RC); 7318 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 7319 .addReg(ptrA).addReg(ptrB); 7320 } else { 7321 Ptr1Reg = ptrB; 7322 } 7323 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 7324 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 7325 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 7326 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 7327 if (is64bit) 7328 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 7329 .addReg(Ptr1Reg).addImm(0).addImm(61); 7330 else 7331 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 7332 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 7333 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 7334 .addReg(newval).addReg(ShiftReg); 7335 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 7336 .addReg(oldval).addReg(ShiftReg); 7337 if (is8bit) 7338 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 7339 else { 7340 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 7341 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 7342 .addReg(Mask3Reg).addImm(65535); 7343 } 7344 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 7345 .addReg(Mask2Reg).addReg(ShiftReg); 7346 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 7347 .addReg(NewVal2Reg).addReg(MaskReg); 7348 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 7349 .addReg(OldVal2Reg).addReg(MaskReg); 7350 7351 BB = loop1MBB; 7352 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 7353 .addReg(ZeroReg).addReg(PtrReg); 7354 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 7355 .addReg(TmpDestReg).addReg(MaskReg); 7356 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 7357 .addReg(TmpReg).addReg(OldVal3Reg); 7358 BuildMI(BB, dl, TII->get(PPC::BCC)) 7359 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 7360 BB->addSuccessor(loop2MBB); 7361 BB->addSuccessor(midMBB); 7362 7363 BB = loop2MBB; 7364 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 7365 .addReg(TmpDestReg).addReg(MaskReg); 7366 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 7367 .addReg(Tmp2Reg).addReg(NewVal3Reg); 7368 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 7369 .addReg(ZeroReg).addReg(PtrReg); 7370 BuildMI(BB, dl, TII->get(PPC::BCC)) 7371 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 7372 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 7373 BB->addSuccessor(loop1MBB); 7374 BB->addSuccessor(exitMBB); 7375 7376 BB = midMBB; 7377 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 7378 .addReg(ZeroReg).addReg(PtrReg); 7379 BB->addSuccessor(exitMBB); 7380 7381 // exitMBB: 7382 // ... 7383 BB = exitMBB; 7384 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 7385 .addReg(ShiftReg); 7386 } else if (MI->getOpcode() == PPC::FADDrtz) { 7387 // This pseudo performs an FADD with rounding mode temporarily forced 7388 // to round-to-zero. We emit this via custom inserter since the FPSCR 7389 // is not modeled at the SelectionDAG level. 7390 unsigned Dest = MI->getOperand(0).getReg(); 7391 unsigned Src1 = MI->getOperand(1).getReg(); 7392 unsigned Src2 = MI->getOperand(2).getReg(); 7393 DebugLoc dl = MI->getDebugLoc(); 7394 7395 MachineRegisterInfo &RegInfo = F->getRegInfo(); 7396 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 7397 7398 // Save FPSCR value. 7399 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 7400 7401 // Set rounding mode to round-to-zero. 7402 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 7403 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 7404 7405 // Perform addition. 7406 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 7407 7408 // Restore FPSCR value. 7409 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg); 7410 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT || 7411 MI->getOpcode() == PPC::ANDIo_1_GT_BIT || 7412 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 7413 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) { 7414 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 7415 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ? 7416 PPC::ANDIo8 : PPC::ANDIo; 7417 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT || 7418 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8); 7419 7420 MachineRegisterInfo &RegInfo = F->getRegInfo(); 7421 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 7422 &PPC::GPRCRegClass : 7423 &PPC::G8RCRegClass); 7424 7425 DebugLoc dl = MI->getDebugLoc(); 7426 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 7427 .addReg(MI->getOperand(1).getReg()).addImm(1); 7428 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 7429 MI->getOperand(0).getReg()) 7430 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 7431 } else { 7432 llvm_unreachable("Unexpected instr type to insert"); 7433 } 7434 7435 MI->eraseFromParent(); // The pseudo instruction is gone now. 7436 return BB; 7437 } 7438 7439 //===----------------------------------------------------------------------===// 7440 // Target Optimization Hooks 7441 //===----------------------------------------------------------------------===// 7442 7443 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op, 7444 DAGCombinerInfo &DCI) const { 7445 if (DCI.isAfterLegalizeVectorOps()) 7446 return SDValue(); 7447 7448 EVT VT = Op.getValueType(); 7449 7450 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 7451 (VT == MVT::f64 && Subtarget.hasFRE()) || 7452 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 7453 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 7454 7455 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 7456 // For the reciprocal, we need to find the zero of the function: 7457 // F(X) = A X - 1 [which has a zero at X = 1/A] 7458 // => 7459 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 7460 // does not require additional intermediate precision] 7461 7462 // Convergence is quadratic, so we essentially double the number of digits 7463 // correct after every iteration. The minimum architected relative 7464 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has 7465 // 23 digits and double has 52 digits. 7466 int Iterations = Subtarget.hasRecipPrec() ? 1 : 3; 7467 if (VT.getScalarType() == MVT::f64) 7468 ++Iterations; 7469 7470 SelectionDAG &DAG = DCI.DAG; 7471 SDLoc dl(Op); 7472 7473 SDValue FPOne = 7474 DAG.getConstantFP(1.0, VT.getScalarType()); 7475 if (VT.isVector()) { 7476 assert(VT.getVectorNumElements() == 4 && 7477 "Unknown vector type"); 7478 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, 7479 FPOne, FPOne, FPOne, FPOne); 7480 } 7481 7482 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op); 7483 DCI.AddToWorklist(Est.getNode()); 7484 7485 // Newton iterations: Est = Est + Est (1 - Arg * Est) 7486 for (int i = 0; i < Iterations; ++i) { 7487 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est); 7488 DCI.AddToWorklist(NewEst.getNode()); 7489 7490 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst); 7491 DCI.AddToWorklist(NewEst.getNode()); 7492 7493 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst); 7494 DCI.AddToWorklist(NewEst.getNode()); 7495 7496 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst); 7497 DCI.AddToWorklist(Est.getNode()); 7498 } 7499 7500 return Est; 7501 } 7502 7503 return SDValue(); 7504 } 7505 7506 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op, 7507 DAGCombinerInfo &DCI) const { 7508 if (DCI.isAfterLegalizeVectorOps()) 7509 return SDValue(); 7510 7511 EVT VT = Op.getValueType(); 7512 7513 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 7514 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 7515 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 7516 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 7517 7518 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 7519 // For the reciprocal sqrt, we need to find the zero of the function: 7520 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 7521 // => 7522 // X_{i+1} = X_i (1.5 - A X_i^2 / 2) 7523 // As a result, we precompute A/2 prior to the iteration loop. 7524 7525 // Convergence is quadratic, so we essentially double the number of digits 7526 // correct after every iteration. The minimum architected relative 7527 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has 7528 // 23 digits and double has 52 digits. 7529 int Iterations = Subtarget.hasRecipPrec() ? 1 : 3; 7530 if (VT.getScalarType() == MVT::f64) 7531 ++Iterations; 7532 7533 SelectionDAG &DAG = DCI.DAG; 7534 SDLoc dl(Op); 7535 7536 SDValue FPThreeHalves = 7537 DAG.getConstantFP(1.5, VT.getScalarType()); 7538 if (VT.isVector()) { 7539 assert(VT.getVectorNumElements() == 4 && 7540 "Unknown vector type"); 7541 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, 7542 FPThreeHalves, FPThreeHalves, 7543 FPThreeHalves, FPThreeHalves); 7544 } 7545 7546 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op); 7547 DCI.AddToWorklist(Est.getNode()); 7548 7549 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that 7550 // this entire sequence requires only one FP constant. 7551 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op); 7552 DCI.AddToWorklist(HalfArg.getNode()); 7553 7554 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op); 7555 DCI.AddToWorklist(HalfArg.getNode()); 7556 7557 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 7558 for (int i = 0; i < Iterations; ++i) { 7559 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est); 7560 DCI.AddToWorklist(NewEst.getNode()); 7561 7562 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst); 7563 DCI.AddToWorklist(NewEst.getNode()); 7564 7565 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst); 7566 DCI.AddToWorklist(NewEst.getNode()); 7567 7568 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst); 7569 DCI.AddToWorklist(Est.getNode()); 7570 } 7571 7572 return Est; 7573 } 7574 7575 return SDValue(); 7576 } 7577 7578 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 7579 // not enforce equality of the chain operands. 7580 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base, 7581 unsigned Bytes, int Dist, 7582 SelectionDAG &DAG) { 7583 EVT VT = LS->getMemoryVT(); 7584 if (VT.getSizeInBits() / 8 != Bytes) 7585 return false; 7586 7587 SDValue Loc = LS->getBasePtr(); 7588 SDValue BaseLoc = Base->getBasePtr(); 7589 if (Loc.getOpcode() == ISD::FrameIndex) { 7590 if (BaseLoc.getOpcode() != ISD::FrameIndex) 7591 return false; 7592 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7593 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 7594 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 7595 int FS = MFI->getObjectSize(FI); 7596 int BFS = MFI->getObjectSize(BFI); 7597 if (FS != BFS || FS != (int)Bytes) return false; 7598 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes); 7599 } 7600 7601 // Handle X+C 7602 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc && 7603 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes) 7604 return true; 7605 7606 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7607 const GlobalValue *GV1 = nullptr; 7608 const GlobalValue *GV2 = nullptr; 7609 int64_t Offset1 = 0; 7610 int64_t Offset2 = 0; 7611 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 7612 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 7613 if (isGA1 && isGA2 && GV1 == GV2) 7614 return Offset1 == (Offset2 + Dist*Bytes); 7615 return false; 7616 } 7617 7618 // Return true is there is a nearyby consecutive load to the one provided 7619 // (regardless of alignment). We search up and down the chain, looking though 7620 // token factors and other loads (but nothing else). As a result, a true 7621 // results indicates that it is safe to create a new consecutive load adjacent 7622 // to the load provided. 7623 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 7624 SDValue Chain = LD->getChain(); 7625 EVT VT = LD->getMemoryVT(); 7626 7627 SmallSet<SDNode *, 16> LoadRoots; 7628 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 7629 SmallSet<SDNode *, 16> Visited; 7630 7631 // First, search up the chain, branching to follow all token-factor operands. 7632 // If we find a consecutive load, then we're done, otherwise, record all 7633 // nodes just above the top-level loads and token factors. 7634 while (!Queue.empty()) { 7635 SDNode *ChainNext = Queue.pop_back_val(); 7636 if (!Visited.insert(ChainNext)) 7637 continue; 7638 7639 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) { 7640 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 7641 return true; 7642 7643 if (!Visited.count(ChainLD->getChain().getNode())) 7644 Queue.push_back(ChainLD->getChain().getNode()); 7645 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 7646 for (const SDUse &O : ChainNext->ops()) 7647 if (!Visited.count(O.getNode())) 7648 Queue.push_back(O.getNode()); 7649 } else 7650 LoadRoots.insert(ChainNext); 7651 } 7652 7653 // Second, search down the chain, starting from the top-level nodes recorded 7654 // in the first phase. These top-level nodes are the nodes just above all 7655 // loads and token factors. Starting with their uses, recursively look though 7656 // all loads (just the chain uses) and token factors to find a consecutive 7657 // load. 7658 Visited.clear(); 7659 Queue.clear(); 7660 7661 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 7662 IE = LoadRoots.end(); I != IE; ++I) { 7663 Queue.push_back(*I); 7664 7665 while (!Queue.empty()) { 7666 SDNode *LoadRoot = Queue.pop_back_val(); 7667 if (!Visited.insert(LoadRoot)) 7668 continue; 7669 7670 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot)) 7671 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 7672 return true; 7673 7674 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 7675 UE = LoadRoot->use_end(); UI != UE; ++UI) 7676 if (((isa<LoadSDNode>(*UI) && 7677 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) || 7678 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 7679 Queue.push_back(*UI); 7680 } 7681 } 7682 7683 return false; 7684 } 7685 7686 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 7687 DAGCombinerInfo &DCI) const { 7688 SelectionDAG &DAG = DCI.DAG; 7689 SDLoc dl(N); 7690 7691 assert(Subtarget.useCRBits() && 7692 "Expecting to be tracking CR bits"); 7693 // If we're tracking CR bits, we need to be careful that we don't have: 7694 // trunc(binary-ops(zext(x), zext(y))) 7695 // or 7696 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 7697 // such that we're unnecessarily moving things into GPRs when it would be 7698 // better to keep them in CR bits. 7699 7700 // Note that trunc here can be an actual i1 trunc, or can be the effective 7701 // truncation that comes from a setcc or select_cc. 7702 if (N->getOpcode() == ISD::TRUNCATE && 7703 N->getValueType(0) != MVT::i1) 7704 return SDValue(); 7705 7706 if (N->getOperand(0).getValueType() != MVT::i32 && 7707 N->getOperand(0).getValueType() != MVT::i64) 7708 return SDValue(); 7709 7710 if (N->getOpcode() == ISD::SETCC || 7711 N->getOpcode() == ISD::SELECT_CC) { 7712 // If we're looking at a comparison, then we need to make sure that the 7713 // high bits (all except for the first) don't matter the result. 7714 ISD::CondCode CC = 7715 cast<CondCodeSDNode>(N->getOperand( 7716 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 7717 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 7718 7719 if (ISD::isSignedIntSetCC(CC)) { 7720 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 7721 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 7722 return SDValue(); 7723 } else if (ISD::isUnsignedIntSetCC(CC)) { 7724 if (!DAG.MaskedValueIsZero(N->getOperand(0), 7725 APInt::getHighBitsSet(OpBits, OpBits-1)) || 7726 !DAG.MaskedValueIsZero(N->getOperand(1), 7727 APInt::getHighBitsSet(OpBits, OpBits-1))) 7728 return SDValue(); 7729 } else { 7730 // This is neither a signed nor an unsigned comparison, just make sure 7731 // that the high bits are equal. 7732 APInt Op1Zero, Op1One; 7733 APInt Op2Zero, Op2One; 7734 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One); 7735 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One); 7736 7737 // We don't really care about what is known about the first bit (if 7738 // anything), so clear it in all masks prior to comparing them. 7739 Op1Zero.clearBit(0); Op1One.clearBit(0); 7740 Op2Zero.clearBit(0); Op2One.clearBit(0); 7741 7742 if (Op1Zero != Op2Zero || Op1One != Op2One) 7743 return SDValue(); 7744 } 7745 } 7746 7747 // We now know that the higher-order bits are irrelevant, we just need to 7748 // make sure that all of the intermediate operations are bit operations, and 7749 // all inputs are extensions. 7750 if (N->getOperand(0).getOpcode() != ISD::AND && 7751 N->getOperand(0).getOpcode() != ISD::OR && 7752 N->getOperand(0).getOpcode() != ISD::XOR && 7753 N->getOperand(0).getOpcode() != ISD::SELECT && 7754 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 7755 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 7756 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 7757 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 7758 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 7759 return SDValue(); 7760 7761 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 7762 N->getOperand(1).getOpcode() != ISD::AND && 7763 N->getOperand(1).getOpcode() != ISD::OR && 7764 N->getOperand(1).getOpcode() != ISD::XOR && 7765 N->getOperand(1).getOpcode() != ISD::SELECT && 7766 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 7767 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 7768 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 7769 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 7770 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 7771 return SDValue(); 7772 7773 SmallVector<SDValue, 4> Inputs; 7774 SmallVector<SDValue, 8> BinOps, PromOps; 7775 SmallPtrSet<SDNode *, 16> Visited; 7776 7777 for (unsigned i = 0; i < 2; ++i) { 7778 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 7779 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 7780 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 7781 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 7782 isa<ConstantSDNode>(N->getOperand(i))) 7783 Inputs.push_back(N->getOperand(i)); 7784 else 7785 BinOps.push_back(N->getOperand(i)); 7786 7787 if (N->getOpcode() == ISD::TRUNCATE) 7788 break; 7789 } 7790 7791 // Visit all inputs, collect all binary operations (and, or, xor and 7792 // select) that are all fed by extensions. 7793 while (!BinOps.empty()) { 7794 SDValue BinOp = BinOps.back(); 7795 BinOps.pop_back(); 7796 7797 if (!Visited.insert(BinOp.getNode())) 7798 continue; 7799 7800 PromOps.push_back(BinOp); 7801 7802 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 7803 // The condition of the select is not promoted. 7804 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 7805 continue; 7806 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 7807 continue; 7808 7809 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 7810 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 7811 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 7812 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 7813 isa<ConstantSDNode>(BinOp.getOperand(i))) { 7814 Inputs.push_back(BinOp.getOperand(i)); 7815 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 7816 BinOp.getOperand(i).getOpcode() == ISD::OR || 7817 BinOp.getOperand(i).getOpcode() == ISD::XOR || 7818 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 7819 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 7820 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 7821 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 7822 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 7823 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 7824 BinOps.push_back(BinOp.getOperand(i)); 7825 } else { 7826 // We have an input that is not an extension or another binary 7827 // operation; we'll abort this transformation. 7828 return SDValue(); 7829 } 7830 } 7831 } 7832 7833 // Make sure that this is a self-contained cluster of operations (which 7834 // is not quite the same thing as saying that everything has only one 7835 // use). 7836 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 7837 if (isa<ConstantSDNode>(Inputs[i])) 7838 continue; 7839 7840 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 7841 UE = Inputs[i].getNode()->use_end(); 7842 UI != UE; ++UI) { 7843 SDNode *User = *UI; 7844 if (User != N && !Visited.count(User)) 7845 return SDValue(); 7846 7847 // Make sure that we're not going to promote the non-output-value 7848 // operand(s) or SELECT or SELECT_CC. 7849 // FIXME: Although we could sometimes handle this, and it does occur in 7850 // practice that one of the condition inputs to the select is also one of 7851 // the outputs, we currently can't deal with this. 7852 if (User->getOpcode() == ISD::SELECT) { 7853 if (User->getOperand(0) == Inputs[i]) 7854 return SDValue(); 7855 } else if (User->getOpcode() == ISD::SELECT_CC) { 7856 if (User->getOperand(0) == Inputs[i] || 7857 User->getOperand(1) == Inputs[i]) 7858 return SDValue(); 7859 } 7860 } 7861 } 7862 7863 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 7864 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 7865 UE = PromOps[i].getNode()->use_end(); 7866 UI != UE; ++UI) { 7867 SDNode *User = *UI; 7868 if (User != N && !Visited.count(User)) 7869 return SDValue(); 7870 7871 // Make sure that we're not going to promote the non-output-value 7872 // operand(s) or SELECT or SELECT_CC. 7873 // FIXME: Although we could sometimes handle this, and it does occur in 7874 // practice that one of the condition inputs to the select is also one of 7875 // the outputs, we currently can't deal with this. 7876 if (User->getOpcode() == ISD::SELECT) { 7877 if (User->getOperand(0) == PromOps[i]) 7878 return SDValue(); 7879 } else if (User->getOpcode() == ISD::SELECT_CC) { 7880 if (User->getOperand(0) == PromOps[i] || 7881 User->getOperand(1) == PromOps[i]) 7882 return SDValue(); 7883 } 7884 } 7885 } 7886 7887 // Replace all inputs with the extension operand. 7888 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 7889 // Constants may have users outside the cluster of to-be-promoted nodes, 7890 // and so we need to replace those as we do the promotions. 7891 if (isa<ConstantSDNode>(Inputs[i])) 7892 continue; 7893 else 7894 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 7895 } 7896 7897 // Replace all operations (these are all the same, but have a different 7898 // (i1) return type). DAG.getNode will validate that the types of 7899 // a binary operator match, so go through the list in reverse so that 7900 // we've likely promoted both operands first. Any intermediate truncations or 7901 // extensions disappear. 7902 while (!PromOps.empty()) { 7903 SDValue PromOp = PromOps.back(); 7904 PromOps.pop_back(); 7905 7906 if (PromOp.getOpcode() == ISD::TRUNCATE || 7907 PromOp.getOpcode() == ISD::SIGN_EXTEND || 7908 PromOp.getOpcode() == ISD::ZERO_EXTEND || 7909 PromOp.getOpcode() == ISD::ANY_EXTEND) { 7910 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 7911 PromOp.getOperand(0).getValueType() != MVT::i1) { 7912 // The operand is not yet ready (see comment below). 7913 PromOps.insert(PromOps.begin(), PromOp); 7914 continue; 7915 } 7916 7917 SDValue RepValue = PromOp.getOperand(0); 7918 if (isa<ConstantSDNode>(RepValue)) 7919 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 7920 7921 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 7922 continue; 7923 } 7924 7925 unsigned C; 7926 switch (PromOp.getOpcode()) { 7927 default: C = 0; break; 7928 case ISD::SELECT: C = 1; break; 7929 case ISD::SELECT_CC: C = 2; break; 7930 } 7931 7932 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 7933 PromOp.getOperand(C).getValueType() != MVT::i1) || 7934 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 7935 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 7936 // The to-be-promoted operands of this node have not yet been 7937 // promoted (this should be rare because we're going through the 7938 // list backward, but if one of the operands has several users in 7939 // this cluster of to-be-promoted nodes, it is possible). 7940 PromOps.insert(PromOps.begin(), PromOp); 7941 continue; 7942 } 7943 7944 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 7945 PromOp.getNode()->op_end()); 7946 7947 // If there are any constant inputs, make sure they're replaced now. 7948 for (unsigned i = 0; i < 2; ++i) 7949 if (isa<ConstantSDNode>(Ops[C+i])) 7950 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 7951 7952 DAG.ReplaceAllUsesOfValueWith(PromOp, 7953 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 7954 } 7955 7956 // Now we're left with the initial truncation itself. 7957 if (N->getOpcode() == ISD::TRUNCATE) 7958 return N->getOperand(0); 7959 7960 // Otherwise, this is a comparison. The operands to be compared have just 7961 // changed type (to i1), but everything else is the same. 7962 return SDValue(N, 0); 7963 } 7964 7965 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 7966 DAGCombinerInfo &DCI) const { 7967 SelectionDAG &DAG = DCI.DAG; 7968 SDLoc dl(N); 7969 7970 // If we're tracking CR bits, we need to be careful that we don't have: 7971 // zext(binary-ops(trunc(x), trunc(y))) 7972 // or 7973 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 7974 // such that we're unnecessarily moving things into CR bits that can more 7975 // efficiently stay in GPRs. Note that if we're not certain that the high 7976 // bits are set as required by the final extension, we still may need to do 7977 // some masking to get the proper behavior. 7978 7979 // This same functionality is important on PPC64 when dealing with 7980 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 7981 // the return values of functions. Because it is so similar, it is handled 7982 // here as well. 7983 7984 if (N->getValueType(0) != MVT::i32 && 7985 N->getValueType(0) != MVT::i64) 7986 return SDValue(); 7987 7988 if (!((N->getOperand(0).getValueType() == MVT::i1 && 7989 Subtarget.useCRBits()) || 7990 (N->getOperand(0).getValueType() == MVT::i32 && 7991 Subtarget.isPPC64()))) 7992 return SDValue(); 7993 7994 if (N->getOperand(0).getOpcode() != ISD::AND && 7995 N->getOperand(0).getOpcode() != ISD::OR && 7996 N->getOperand(0).getOpcode() != ISD::XOR && 7997 N->getOperand(0).getOpcode() != ISD::SELECT && 7998 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 7999 return SDValue(); 8000 8001 SmallVector<SDValue, 4> Inputs; 8002 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 8003 SmallPtrSet<SDNode *, 16> Visited; 8004 8005 // Visit all inputs, collect all binary operations (and, or, xor and 8006 // select) that are all fed by truncations. 8007 while (!BinOps.empty()) { 8008 SDValue BinOp = BinOps.back(); 8009 BinOps.pop_back(); 8010 8011 if (!Visited.insert(BinOp.getNode())) 8012 continue; 8013 8014 PromOps.push_back(BinOp); 8015 8016 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 8017 // The condition of the select is not promoted. 8018 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 8019 continue; 8020 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 8021 continue; 8022 8023 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 8024 isa<ConstantSDNode>(BinOp.getOperand(i))) { 8025 Inputs.push_back(BinOp.getOperand(i)); 8026 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 8027 BinOp.getOperand(i).getOpcode() == ISD::OR || 8028 BinOp.getOperand(i).getOpcode() == ISD::XOR || 8029 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 8030 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 8031 BinOps.push_back(BinOp.getOperand(i)); 8032 } else { 8033 // We have an input that is not a truncation or another binary 8034 // operation; we'll abort this transformation. 8035 return SDValue(); 8036 } 8037 } 8038 } 8039 8040 // Make sure that this is a self-contained cluster of operations (which 8041 // is not quite the same thing as saying that everything has only one 8042 // use). 8043 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 8044 if (isa<ConstantSDNode>(Inputs[i])) 8045 continue; 8046 8047 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 8048 UE = Inputs[i].getNode()->use_end(); 8049 UI != UE; ++UI) { 8050 SDNode *User = *UI; 8051 if (User != N && !Visited.count(User)) 8052 return SDValue(); 8053 8054 // Make sure that we're not going to promote the non-output-value 8055 // operand(s) or SELECT or SELECT_CC. 8056 // FIXME: Although we could sometimes handle this, and it does occur in 8057 // practice that one of the condition inputs to the select is also one of 8058 // the outputs, we currently can't deal with this. 8059 if (User->getOpcode() == ISD::SELECT) { 8060 if (User->getOperand(0) == Inputs[i]) 8061 return SDValue(); 8062 } else if (User->getOpcode() == ISD::SELECT_CC) { 8063 if (User->getOperand(0) == Inputs[i] || 8064 User->getOperand(1) == Inputs[i]) 8065 return SDValue(); 8066 } 8067 } 8068 } 8069 8070 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 8071 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 8072 UE = PromOps[i].getNode()->use_end(); 8073 UI != UE; ++UI) { 8074 SDNode *User = *UI; 8075 if (User != N && !Visited.count(User)) 8076 return SDValue(); 8077 8078 // Make sure that we're not going to promote the non-output-value 8079 // operand(s) or SELECT or SELECT_CC. 8080 // FIXME: Although we could sometimes handle this, and it does occur in 8081 // practice that one of the condition inputs to the select is also one of 8082 // the outputs, we currently can't deal with this. 8083 if (User->getOpcode() == ISD::SELECT) { 8084 if (User->getOperand(0) == PromOps[i]) 8085 return SDValue(); 8086 } else if (User->getOpcode() == ISD::SELECT_CC) { 8087 if (User->getOperand(0) == PromOps[i] || 8088 User->getOperand(1) == PromOps[i]) 8089 return SDValue(); 8090 } 8091 } 8092 } 8093 8094 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 8095 bool ReallyNeedsExt = false; 8096 if (N->getOpcode() != ISD::ANY_EXTEND) { 8097 // If all of the inputs are not already sign/zero extended, then 8098 // we'll still need to do that at the end. 8099 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 8100 if (isa<ConstantSDNode>(Inputs[i])) 8101 continue; 8102 8103 unsigned OpBits = 8104 Inputs[i].getOperand(0).getValueSizeInBits(); 8105 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 8106 8107 if ((N->getOpcode() == ISD::ZERO_EXTEND && 8108 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 8109 APInt::getHighBitsSet(OpBits, 8110 OpBits-PromBits))) || 8111 (N->getOpcode() == ISD::SIGN_EXTEND && 8112 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 8113 (OpBits-(PromBits-1)))) { 8114 ReallyNeedsExt = true; 8115 break; 8116 } 8117 } 8118 } 8119 8120 // Replace all inputs, either with the truncation operand, or a 8121 // truncation or extension to the final output type. 8122 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 8123 // Constant inputs need to be replaced with the to-be-promoted nodes that 8124 // use them because they might have users outside of the cluster of 8125 // promoted nodes. 8126 if (isa<ConstantSDNode>(Inputs[i])) 8127 continue; 8128 8129 SDValue InSrc = Inputs[i].getOperand(0); 8130 if (Inputs[i].getValueType() == N->getValueType(0)) 8131 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 8132 else if (N->getOpcode() == ISD::SIGN_EXTEND) 8133 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 8134 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 8135 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8136 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 8137 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 8138 else 8139 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 8140 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 8141 } 8142 8143 // Replace all operations (these are all the same, but have a different 8144 // (promoted) return type). DAG.getNode will validate that the types of 8145 // a binary operator match, so go through the list in reverse so that 8146 // we've likely promoted both operands first. 8147 while (!PromOps.empty()) { 8148 SDValue PromOp = PromOps.back(); 8149 PromOps.pop_back(); 8150 8151 unsigned C; 8152 switch (PromOp.getOpcode()) { 8153 default: C = 0; break; 8154 case ISD::SELECT: C = 1; break; 8155 case ISD::SELECT_CC: C = 2; break; 8156 } 8157 8158 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 8159 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 8160 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 8161 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 8162 // The to-be-promoted operands of this node have not yet been 8163 // promoted (this should be rare because we're going through the 8164 // list backward, but if one of the operands has several users in 8165 // this cluster of to-be-promoted nodes, it is possible). 8166 PromOps.insert(PromOps.begin(), PromOp); 8167 continue; 8168 } 8169 8170 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 8171 PromOp.getNode()->op_end()); 8172 8173 // If this node has constant inputs, then they'll need to be promoted here. 8174 for (unsigned i = 0; i < 2; ++i) { 8175 if (!isa<ConstantSDNode>(Ops[C+i])) 8176 continue; 8177 if (Ops[C+i].getValueType() == N->getValueType(0)) 8178 continue; 8179 8180 if (N->getOpcode() == ISD::SIGN_EXTEND) 8181 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 8182 else if (N->getOpcode() == ISD::ZERO_EXTEND) 8183 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 8184 else 8185 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 8186 } 8187 8188 DAG.ReplaceAllUsesOfValueWith(PromOp, 8189 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 8190 } 8191 8192 // Now we're left with the initial extension itself. 8193 if (!ReallyNeedsExt) 8194 return N->getOperand(0); 8195 8196 // To zero extend, just mask off everything except for the first bit (in the 8197 // i1 case). 8198 if (N->getOpcode() == ISD::ZERO_EXTEND) 8199 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 8200 DAG.getConstant(APInt::getLowBitsSet( 8201 N->getValueSizeInBits(0), PromBits), 8202 N->getValueType(0))); 8203 8204 assert(N->getOpcode() == ISD::SIGN_EXTEND && 8205 "Invalid extension type"); 8206 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0)); 8207 SDValue ShiftCst = 8208 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy); 8209 return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 8210 DAG.getNode(ISD::SHL, dl, N->getValueType(0), 8211 N->getOperand(0), ShiftCst), ShiftCst); 8212 } 8213 8214 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 8215 DAGCombinerInfo &DCI) const { 8216 const TargetMachine &TM = getTargetMachine(); 8217 SelectionDAG &DAG = DCI.DAG; 8218 SDLoc dl(N); 8219 switch (N->getOpcode()) { 8220 default: break; 8221 case PPCISD::SHL: 8222 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 8223 if (C->isNullValue()) // 0 << V -> 0. 8224 return N->getOperand(0); 8225 } 8226 break; 8227 case PPCISD::SRL: 8228 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 8229 if (C->isNullValue()) // 0 >>u V -> 0. 8230 return N->getOperand(0); 8231 } 8232 break; 8233 case PPCISD::SRA: 8234 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 8235 if (C->isNullValue() || // 0 >>s V -> 0. 8236 C->isAllOnesValue()) // -1 >>s V -> -1. 8237 return N->getOperand(0); 8238 } 8239 break; 8240 case ISD::SIGN_EXTEND: 8241 case ISD::ZERO_EXTEND: 8242 case ISD::ANY_EXTEND: 8243 return DAGCombineExtBoolTrunc(N, DCI); 8244 case ISD::TRUNCATE: 8245 case ISD::SETCC: 8246 case ISD::SELECT_CC: 8247 return DAGCombineTruncBoolExt(N, DCI); 8248 case ISD::FDIV: { 8249 assert(TM.Options.UnsafeFPMath && 8250 "Reciprocal estimates require UnsafeFPMath"); 8251 8252 if (N->getOperand(1).getOpcode() == ISD::FSQRT) { 8253 SDValue RV = 8254 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI); 8255 if (RV.getNode()) { 8256 DCI.AddToWorklist(RV.getNode()); 8257 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0), 8258 N->getOperand(0), RV); 8259 } 8260 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND && 8261 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) { 8262 SDValue RV = 8263 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0), 8264 DCI); 8265 if (RV.getNode()) { 8266 DCI.AddToWorklist(RV.getNode()); 8267 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)), 8268 N->getValueType(0), RV); 8269 DCI.AddToWorklist(RV.getNode()); 8270 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0), 8271 N->getOperand(0), RV); 8272 } 8273 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND && 8274 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) { 8275 SDValue RV = 8276 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0), 8277 DCI); 8278 if (RV.getNode()) { 8279 DCI.AddToWorklist(RV.getNode()); 8280 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)), 8281 N->getValueType(0), RV, 8282 N->getOperand(1).getOperand(1)); 8283 DCI.AddToWorklist(RV.getNode()); 8284 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0), 8285 N->getOperand(0), RV); 8286 } 8287 } 8288 8289 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI); 8290 if (RV.getNode()) { 8291 DCI.AddToWorklist(RV.getNode()); 8292 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0), 8293 N->getOperand(0), RV); 8294 } 8295 8296 } 8297 break; 8298 case ISD::FSQRT: { 8299 assert(TM.Options.UnsafeFPMath && 8300 "Reciprocal estimates require UnsafeFPMath"); 8301 8302 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the 8303 // reciprocal sqrt. 8304 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI); 8305 if (RV.getNode()) { 8306 DCI.AddToWorklist(RV.getNode()); 8307 RV = DAGCombineFastRecip(RV, DCI); 8308 if (RV.getNode()) { 8309 // Unfortunately, RV is now NaN if the input was exactly 0. Select out 8310 // this case and force the answer to 0. 8311 8312 EVT VT = RV.getValueType(); 8313 8314 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType()); 8315 if (VT.isVector()) { 8316 assert(VT.getVectorNumElements() == 4 && "Unknown vector type"); 8317 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero); 8318 } 8319 8320 SDValue ZeroCmp = 8321 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT), 8322 N->getOperand(0), Zero, ISD::SETEQ); 8323 DCI.AddToWorklist(ZeroCmp.getNode()); 8324 DCI.AddToWorklist(RV.getNode()); 8325 8326 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT, 8327 ZeroCmp, Zero, RV); 8328 return RV; 8329 } 8330 } 8331 8332 } 8333 break; 8334 case ISD::SINT_TO_FP: 8335 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) { 8336 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) { 8337 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores. 8338 // We allow the src/dst to be either f32/f64, but the intermediate 8339 // type must be i64. 8340 if (N->getOperand(0).getValueType() == MVT::i64 && 8341 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) { 8342 SDValue Val = N->getOperand(0).getOperand(0); 8343 if (Val.getValueType() == MVT::f32) { 8344 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 8345 DCI.AddToWorklist(Val.getNode()); 8346 } 8347 8348 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val); 8349 DCI.AddToWorklist(Val.getNode()); 8350 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val); 8351 DCI.AddToWorklist(Val.getNode()); 8352 if (N->getValueType(0) == MVT::f32) { 8353 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val, 8354 DAG.getIntPtrConstant(0)); 8355 DCI.AddToWorklist(Val.getNode()); 8356 } 8357 return Val; 8358 } else if (N->getOperand(0).getValueType() == MVT::i32) { 8359 // If the intermediate type is i32, we can avoid the load/store here 8360 // too. 8361 } 8362 } 8363 } 8364 break; 8365 case ISD::STORE: 8366 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 8367 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() && 8368 !cast<StoreSDNode>(N)->isTruncatingStore() && 8369 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 8370 N->getOperand(1).getValueType() == MVT::i32 && 8371 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 8372 SDValue Val = N->getOperand(1).getOperand(0); 8373 if (Val.getValueType() == MVT::f32) { 8374 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 8375 DCI.AddToWorklist(Val.getNode()); 8376 } 8377 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 8378 DCI.AddToWorklist(Val.getNode()); 8379 8380 SDValue Ops[] = { 8381 N->getOperand(0), Val, N->getOperand(2), 8382 DAG.getValueType(N->getOperand(1).getValueType()) 8383 }; 8384 8385 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8386 DAG.getVTList(MVT::Other), Ops, 8387 cast<StoreSDNode>(N)->getMemoryVT(), 8388 cast<StoreSDNode>(N)->getMemOperand()); 8389 DCI.AddToWorklist(Val.getNode()); 8390 return Val; 8391 } 8392 8393 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 8394 if (cast<StoreSDNode>(N)->isUnindexed() && 8395 N->getOperand(1).getOpcode() == ISD::BSWAP && 8396 N->getOperand(1).getNode()->hasOneUse() && 8397 (N->getOperand(1).getValueType() == MVT::i32 || 8398 N->getOperand(1).getValueType() == MVT::i16 || 8399 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() && 8400 TM.getSubtarget<PPCSubtarget>().isPPC64() && 8401 N->getOperand(1).getValueType() == MVT::i64))) { 8402 SDValue BSwapOp = N->getOperand(1).getOperand(0); 8403 // Do an any-extend to 32-bits if this is a half-word input. 8404 if (BSwapOp.getValueType() == MVT::i16) 8405 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 8406 8407 SDValue Ops[] = { 8408 N->getOperand(0), BSwapOp, N->getOperand(2), 8409 DAG.getValueType(N->getOperand(1).getValueType()) 8410 }; 8411 return 8412 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 8413 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 8414 cast<StoreSDNode>(N)->getMemOperand()); 8415 } 8416 break; 8417 case ISD::LOAD: { 8418 LoadSDNode *LD = cast<LoadSDNode>(N); 8419 EVT VT = LD->getValueType(0); 8420 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext()); 8421 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty); 8422 if (ISD::isNON_EXTLoad(N) && VT.isVector() && 8423 TM.getSubtarget<PPCSubtarget>().hasAltivec() && 8424 (VT == MVT::v16i8 || VT == MVT::v8i16 || 8425 VT == MVT::v4i32 || VT == MVT::v4f32) && 8426 LD->getAlignment() < ABIAlignment) { 8427 // This is a type-legal unaligned Altivec load. 8428 SDValue Chain = LD->getChain(); 8429 SDValue Ptr = LD->getBasePtr(); 8430 bool isLittleEndian = Subtarget.isLittleEndian(); 8431 8432 // This implements the loading of unaligned vectors as described in 8433 // the venerable Apple Velocity Engine overview. Specifically: 8434 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 8435 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 8436 // 8437 // The general idea is to expand a sequence of one or more unaligned 8438 // loads into an alignment-based permutation-control instruction (lvsl 8439 // or lvsr), a series of regular vector loads (which always truncate 8440 // their input address to an aligned address), and a series of 8441 // permutations. The results of these permutations are the requested 8442 // loaded values. The trick is that the last "extra" load is not taken 8443 // from the address you might suspect (sizeof(vector) bytes after the 8444 // last requested load), but rather sizeof(vector) - 1 bytes after the 8445 // last requested vector. The point of this is to avoid a page fault if 8446 // the base address happened to be aligned. This works because if the 8447 // base address is aligned, then adding less than a full vector length 8448 // will cause the last vector in the sequence to be (re)loaded. 8449 // Otherwise, the next vector will be fetched as you might suspect was 8450 // necessary. 8451 8452 // We might be able to reuse the permutation generation from 8453 // a different base address offset from this one by an aligned amount. 8454 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 8455 // optimization later. 8456 Intrinsic::ID Intr = (isLittleEndian ? 8457 Intrinsic::ppc_altivec_lvsr : 8458 Intrinsic::ppc_altivec_lvsl); 8459 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8); 8460 8461 // Refine the alignment of the original load (a "new" load created here 8462 // which was identical to the first except for the alignment would be 8463 // merged with the existing node regardless). 8464 MachineFunction &MF = DAG.getMachineFunction(); 8465 MachineMemOperand *MMO = 8466 MF.getMachineMemOperand(LD->getPointerInfo(), 8467 LD->getMemOperand()->getFlags(), 8468 LD->getMemoryVT().getStoreSize(), 8469 ABIAlignment); 8470 LD->refineAlignment(MMO); 8471 SDValue BaseLoad = SDValue(LD, 0); 8472 8473 // Note that the value of IncOffset (which is provided to the next 8474 // load's pointer info offset value, and thus used to calculate the 8475 // alignment), and the value of IncValue (which is actually used to 8476 // increment the pointer value) are different! This is because we 8477 // require the next load to appear to be aligned, even though it 8478 // is actually offset from the base pointer by a lesser amount. 8479 int IncOffset = VT.getSizeInBits() / 8; 8480 int IncValue = IncOffset; 8481 8482 // Walk (both up and down) the chain looking for another load at the real 8483 // (aligned) offset (the alignment of the other load does not matter in 8484 // this case). If found, then do not use the offset reduction trick, as 8485 // that will prevent the loads from being later combined (as they would 8486 // otherwise be duplicates). 8487 if (!findConsecutiveLoad(LD, DAG)) 8488 --IncValue; 8489 8490 SDValue Increment = DAG.getConstant(IncValue, getPointerTy()); 8491 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 8492 8493 SDValue ExtraLoad = 8494 DAG.getLoad(VT, dl, Chain, Ptr, 8495 LD->getPointerInfo().getWithOffset(IncOffset), 8496 LD->isVolatile(), LD->isNonTemporal(), 8497 LD->isInvariant(), ABIAlignment); 8498 8499 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8500 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 8501 8502 if (BaseLoad.getValueType() != MVT::v4i32) 8503 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad); 8504 8505 if (ExtraLoad.getValueType() != MVT::v4i32) 8506 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad); 8507 8508 // Because vperm has a big-endian bias, we must reverse the order 8509 // of the input vectors and complement the permute control vector 8510 // when generating little endian code. We have already handled the 8511 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 8512 // and ExtraLoad here. 8513 SDValue Perm; 8514 if (isLittleEndian) 8515 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm, 8516 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 8517 else 8518 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm, 8519 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 8520 8521 if (VT != MVT::v4i32) 8522 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm); 8523 8524 // Now we need to be really careful about how we update the users of the 8525 // original load. We cannot just call DCI.CombineTo (or 8526 // DAG.ReplaceAllUsesWith for that matter), because the load still has 8527 // uses created here (the permutation for example) that need to stay. 8528 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 8529 while (UI != UE) { 8530 SDUse &Use = UI.getUse(); 8531 SDNode *User = *UI; 8532 // Note: BaseLoad is checked here because it might not be N, but a 8533 // bitcast of N. 8534 if (User == Perm.getNode() || User == BaseLoad.getNode() || 8535 User == TF.getNode() || Use.getResNo() > 1) { 8536 ++UI; 8537 continue; 8538 } 8539 8540 SDValue To = Use.getResNo() ? TF : Perm; 8541 ++UI; 8542 8543 SmallVector<SDValue, 8> Ops; 8544 for (const SDUse &O : User->ops()) { 8545 if (O == Use) 8546 Ops.push_back(To); 8547 else 8548 Ops.push_back(O); 8549 } 8550 8551 DAG.UpdateNodeOperands(User, Ops); 8552 } 8553 8554 return SDValue(N, 0); 8555 } 8556 } 8557 break; 8558 case ISD::INTRINSIC_WO_CHAIN: { 8559 bool isLittleEndian = Subtarget.isLittleEndian(); 8560 Intrinsic::ID Intr = (isLittleEndian ? 8561 Intrinsic::ppc_altivec_lvsr : 8562 Intrinsic::ppc_altivec_lvsl); 8563 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr && 8564 N->getOperand(1)->getOpcode() == ISD::ADD) { 8565 SDValue Add = N->getOperand(1); 8566 8567 if (DAG.MaskedValueIsZero(Add->getOperand(1), 8568 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext( 8569 Add.getValueType().getScalarType().getSizeInBits()))) { 8570 SDNode *BasePtr = Add->getOperand(0).getNode(); 8571 for (SDNode::use_iterator UI = BasePtr->use_begin(), 8572 UE = BasePtr->use_end(); UI != UE; ++UI) { 8573 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 8574 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 8575 Intr) { 8576 // We've found another LVSL/LVSR, and this address is an aligned 8577 // multiple of that one. The results will be the same, so use the 8578 // one we've just found instead. 8579 8580 return SDValue(*UI, 0); 8581 } 8582 } 8583 } 8584 } 8585 } 8586 8587 break; 8588 case ISD::BSWAP: 8589 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 8590 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 8591 N->getOperand(0).hasOneUse() && 8592 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 8593 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() && 8594 TM.getSubtarget<PPCSubtarget>().isPPC64() && 8595 N->getValueType(0) == MVT::i64))) { 8596 SDValue Load = N->getOperand(0); 8597 LoadSDNode *LD = cast<LoadSDNode>(Load); 8598 // Create the byte-swapping load. 8599 SDValue Ops[] = { 8600 LD->getChain(), // Chain 8601 LD->getBasePtr(), // Ptr 8602 DAG.getValueType(N->getValueType(0)) // VT 8603 }; 8604 SDValue BSLoad = 8605 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 8606 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 8607 MVT::i64 : MVT::i32, MVT::Other), 8608 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8609 8610 // If this is an i16 load, insert the truncate. 8611 SDValue ResVal = BSLoad; 8612 if (N->getValueType(0) == MVT::i16) 8613 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 8614 8615 // First, combine the bswap away. This makes the value produced by the 8616 // load dead. 8617 DCI.CombineTo(N, ResVal); 8618 8619 // Next, combine the load away, we give it a bogus result value but a real 8620 // chain result. The result value is dead because the bswap is dead. 8621 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 8622 8623 // Return N so it doesn't get rechecked! 8624 return SDValue(N, 0); 8625 } 8626 8627 break; 8628 case PPCISD::VCMP: { 8629 // If a VCMPo node already exists with exactly the same operands as this 8630 // node, use its result instead of this node (VCMPo computes both a CR6 and 8631 // a normal output). 8632 // 8633 if (!N->getOperand(0).hasOneUse() && 8634 !N->getOperand(1).hasOneUse() && 8635 !N->getOperand(2).hasOneUse()) { 8636 8637 // Scan all of the users of the LHS, looking for VCMPo's that match. 8638 SDNode *VCMPoNode = nullptr; 8639 8640 SDNode *LHSN = N->getOperand(0).getNode(); 8641 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 8642 UI != E; ++UI) 8643 if (UI->getOpcode() == PPCISD::VCMPo && 8644 UI->getOperand(1) == N->getOperand(1) && 8645 UI->getOperand(2) == N->getOperand(2) && 8646 UI->getOperand(0) == N->getOperand(0)) { 8647 VCMPoNode = *UI; 8648 break; 8649 } 8650 8651 // If there is no VCMPo node, or if the flag value has a single use, don't 8652 // transform this. 8653 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 8654 break; 8655 8656 // Look at the (necessarily single) use of the flag value. If it has a 8657 // chain, this transformation is more complex. Note that multiple things 8658 // could use the value result, which we should ignore. 8659 SDNode *FlagUser = nullptr; 8660 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 8661 FlagUser == nullptr; ++UI) { 8662 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 8663 SDNode *User = *UI; 8664 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 8665 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 8666 FlagUser = User; 8667 break; 8668 } 8669 } 8670 } 8671 8672 // If the user is a MFOCRF instruction, we know this is safe. 8673 // Otherwise we give up for right now. 8674 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 8675 return SDValue(VCMPoNode, 0); 8676 } 8677 break; 8678 } 8679 case ISD::BRCOND: { 8680 SDValue Cond = N->getOperand(1); 8681 SDValue Target = N->getOperand(2); 8682 8683 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 8684 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 8685 Intrinsic::ppc_is_decremented_ctr_nonzero) { 8686 8687 // We now need to make the intrinsic dead (it cannot be instruction 8688 // selected). 8689 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 8690 assert(Cond.getNode()->hasOneUse() && 8691 "Counter decrement has more than one use"); 8692 8693 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 8694 N->getOperand(0), Target); 8695 } 8696 } 8697 break; 8698 case ISD::BR_CC: { 8699 // If this is a branch on an altivec predicate comparison, lower this so 8700 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 8701 // lowering is done pre-legalize, because the legalizer lowers the predicate 8702 // compare down to code that is difficult to reassemble. 8703 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 8704 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 8705 8706 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 8707 // value. If so, pass-through the AND to get to the intrinsic. 8708 if (LHS.getOpcode() == ISD::AND && 8709 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 8710 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 8711 Intrinsic::ppc_is_decremented_ctr_nonzero && 8712 isa<ConstantSDNode>(LHS.getOperand(1)) && 8713 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()-> 8714 isZero()) 8715 LHS = LHS.getOperand(0); 8716 8717 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 8718 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 8719 Intrinsic::ppc_is_decremented_ctr_nonzero && 8720 isa<ConstantSDNode>(RHS)) { 8721 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 8722 "Counter decrement comparison is not EQ or NE"); 8723 8724 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 8725 bool isBDNZ = (CC == ISD::SETEQ && Val) || 8726 (CC == ISD::SETNE && !Val); 8727 8728 // We now need to make the intrinsic dead (it cannot be instruction 8729 // selected). 8730 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 8731 assert(LHS.getNode()->hasOneUse() && 8732 "Counter decrement has more than one use"); 8733 8734 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 8735 N->getOperand(0), N->getOperand(4)); 8736 } 8737 8738 int CompareOpc; 8739 bool isDot; 8740 8741 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 8742 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 8743 getAltivecCompareInfo(LHS, CompareOpc, isDot)) { 8744 assert(isDot && "Can't compare against a vector result!"); 8745 8746 // If this is a comparison against something other than 0/1, then we know 8747 // that the condition is never/always true. 8748 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 8749 if (Val != 0 && Val != 1) { 8750 if (CC == ISD::SETEQ) // Cond never true, remove branch. 8751 return N->getOperand(0); 8752 // Always !=, turn it into an unconditional branch. 8753 return DAG.getNode(ISD::BR, dl, MVT::Other, 8754 N->getOperand(0), N->getOperand(4)); 8755 } 8756 8757 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 8758 8759 // Create the PPCISD altivec 'dot' comparison node. 8760 SDValue Ops[] = { 8761 LHS.getOperand(2), // LHS of compare 8762 LHS.getOperand(3), // RHS of compare 8763 DAG.getConstant(CompareOpc, MVT::i32) 8764 }; 8765 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 8766 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 8767 8768 // Unpack the result based on how the target uses it. 8769 PPC::Predicate CompOpc; 8770 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 8771 default: // Can't happen, don't crash on invalid number though. 8772 case 0: // Branch on the value of the EQ bit of CR6. 8773 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 8774 break; 8775 case 1: // Branch on the inverted value of the EQ bit of CR6. 8776 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 8777 break; 8778 case 2: // Branch on the value of the LT bit of CR6. 8779 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 8780 break; 8781 case 3: // Branch on the inverted value of the LT bit of CR6. 8782 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 8783 break; 8784 } 8785 8786 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 8787 DAG.getConstant(CompOpc, MVT::i32), 8788 DAG.getRegister(PPC::CR6, MVT::i32), 8789 N->getOperand(4), CompNode.getValue(1)); 8790 } 8791 break; 8792 } 8793 } 8794 8795 return SDValue(); 8796 } 8797 8798 //===----------------------------------------------------------------------===// 8799 // Inline Assembly Support 8800 //===----------------------------------------------------------------------===// 8801 8802 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8803 APInt &KnownZero, 8804 APInt &KnownOne, 8805 const SelectionDAG &DAG, 8806 unsigned Depth) const { 8807 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0); 8808 switch (Op.getOpcode()) { 8809 default: break; 8810 case PPCISD::LBRX: { 8811 // lhbrx is known to have the top bits cleared out. 8812 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 8813 KnownZero = 0xFFFF0000; 8814 break; 8815 } 8816 case ISD::INTRINSIC_WO_CHAIN: { 8817 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 8818 default: break; 8819 case Intrinsic::ppc_altivec_vcmpbfp_p: 8820 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8821 case Intrinsic::ppc_altivec_vcmpequb_p: 8822 case Intrinsic::ppc_altivec_vcmpequh_p: 8823 case Intrinsic::ppc_altivec_vcmpequw_p: 8824 case Intrinsic::ppc_altivec_vcmpgefp_p: 8825 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8826 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8827 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8828 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8829 case Intrinsic::ppc_altivec_vcmpgtub_p: 8830 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8831 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8832 KnownZero = ~1U; // All bits but the low one are known to be zero. 8833 break; 8834 } 8835 } 8836 } 8837 } 8838 8839 8840 /// getConstraintType - Given a constraint, return the type of 8841 /// constraint it is for this target. 8842 PPCTargetLowering::ConstraintType 8843 PPCTargetLowering::getConstraintType(const std::string &Constraint) const { 8844 if (Constraint.size() == 1) { 8845 switch (Constraint[0]) { 8846 default: break; 8847 case 'b': 8848 case 'r': 8849 case 'f': 8850 case 'v': 8851 case 'y': 8852 return C_RegisterClass; 8853 case 'Z': 8854 // FIXME: While Z does indicate a memory constraint, it specifically 8855 // indicates an r+r address (used in conjunction with the 'y' modifier 8856 // in the replacement string). Currently, we're forcing the base 8857 // register to be r0 in the asm printer (which is interpreted as zero) 8858 // and forming the complete address in the second register. This is 8859 // suboptimal. 8860 return C_Memory; 8861 } 8862 } else if (Constraint == "wc") { // individual CR bits. 8863 return C_RegisterClass; 8864 } else if (Constraint == "wa" || Constraint == "wd" || 8865 Constraint == "wf" || Constraint == "ws") { 8866 return C_RegisterClass; // VSX registers. 8867 } 8868 return TargetLowering::getConstraintType(Constraint); 8869 } 8870 8871 /// Examine constraint type and operand type and determine a weight value. 8872 /// This object must already have been set up with the operand type 8873 /// and the current alternative constraint selected. 8874 TargetLowering::ConstraintWeight 8875 PPCTargetLowering::getSingleConstraintMatchWeight( 8876 AsmOperandInfo &info, const char *constraint) const { 8877 ConstraintWeight weight = CW_Invalid; 8878 Value *CallOperandVal = info.CallOperandVal; 8879 // If we don't have a value, we can't do a match, 8880 // but allow it at the lowest weight. 8881 if (!CallOperandVal) 8882 return CW_Default; 8883 Type *type = CallOperandVal->getType(); 8884 8885 // Look at the constraint type. 8886 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 8887 return CW_Register; // an individual CR bit. 8888 else if ((StringRef(constraint) == "wa" || 8889 StringRef(constraint) == "wd" || 8890 StringRef(constraint) == "wf") && 8891 type->isVectorTy()) 8892 return CW_Register; 8893 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 8894 return CW_Register; 8895 8896 switch (*constraint) { 8897 default: 8898 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 8899 break; 8900 case 'b': 8901 if (type->isIntegerTy()) 8902 weight = CW_Register; 8903 break; 8904 case 'f': 8905 if (type->isFloatTy()) 8906 weight = CW_Register; 8907 break; 8908 case 'd': 8909 if (type->isDoubleTy()) 8910 weight = CW_Register; 8911 break; 8912 case 'v': 8913 if (type->isVectorTy()) 8914 weight = CW_Register; 8915 break; 8916 case 'y': 8917 weight = CW_Register; 8918 break; 8919 case 'Z': 8920 weight = CW_Memory; 8921 break; 8922 } 8923 return weight; 8924 } 8925 8926 std::pair<unsigned, const TargetRegisterClass*> 8927 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 8928 MVT VT) const { 8929 if (Constraint.size() == 1) { 8930 // GCC RS6000 Constraint Letters 8931 switch (Constraint[0]) { 8932 case 'b': // R1-R31 8933 if (VT == MVT::i64 && Subtarget.isPPC64()) 8934 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 8935 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 8936 case 'r': // R0-R31 8937 if (VT == MVT::i64 && Subtarget.isPPC64()) 8938 return std::make_pair(0U, &PPC::G8RCRegClass); 8939 return std::make_pair(0U, &PPC::GPRCRegClass); 8940 case 'f': 8941 if (VT == MVT::f32 || VT == MVT::i32) 8942 return std::make_pair(0U, &PPC::F4RCRegClass); 8943 if (VT == MVT::f64 || VT == MVT::i64) 8944 return std::make_pair(0U, &PPC::F8RCRegClass); 8945 break; 8946 case 'v': 8947 return std::make_pair(0U, &PPC::VRRCRegClass); 8948 case 'y': // crrc 8949 return std::make_pair(0U, &PPC::CRRCRegClass); 8950 } 8951 } else if (Constraint == "wc") { // an individual CR bit. 8952 return std::make_pair(0U, &PPC::CRBITRCRegClass); 8953 } else if (Constraint == "wa" || Constraint == "wd" || 8954 Constraint == "wf") { 8955 return std::make_pair(0U, &PPC::VSRCRegClass); 8956 } else if (Constraint == "ws") { 8957 return std::make_pair(0U, &PPC::VSFRCRegClass); 8958 } 8959 8960 std::pair<unsigned, const TargetRegisterClass*> R = 8961 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 8962 8963 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 8964 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 8965 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 8966 // register. 8967 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 8968 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 8969 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 8970 PPC::GPRCRegClass.contains(R.first)) { 8971 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo(); 8972 return std::make_pair(TRI->getMatchingSuperReg(R.first, 8973 PPC::sub_32, &PPC::G8RCRegClass), 8974 &PPC::G8RCRegClass); 8975 } 8976 8977 return R; 8978 } 8979 8980 8981 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 8982 /// vector. If it is invalid, don't add anything to Ops. 8983 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 8984 std::string &Constraint, 8985 std::vector<SDValue>&Ops, 8986 SelectionDAG &DAG) const { 8987 SDValue Result; 8988 8989 // Only support length 1 constraints. 8990 if (Constraint.length() > 1) return; 8991 8992 char Letter = Constraint[0]; 8993 switch (Letter) { 8994 default: break; 8995 case 'I': 8996 case 'J': 8997 case 'K': 8998 case 'L': 8999 case 'M': 9000 case 'N': 9001 case 'O': 9002 case 'P': { 9003 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 9004 if (!CST) return; // Must be an immediate to match. 9005 unsigned Value = CST->getZExtValue(); 9006 switch (Letter) { 9007 default: llvm_unreachable("Unknown constraint letter!"); 9008 case 'I': // "I" is a signed 16-bit constant. 9009 if ((short)Value == (int)Value) 9010 Result = DAG.getTargetConstant(Value, Op.getValueType()); 9011 break; 9012 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 9013 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 9014 if ((short)Value == 0) 9015 Result = DAG.getTargetConstant(Value, Op.getValueType()); 9016 break; 9017 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 9018 if ((Value >> 16) == 0) 9019 Result = DAG.getTargetConstant(Value, Op.getValueType()); 9020 break; 9021 case 'M': // "M" is a constant that is greater than 31. 9022 if (Value > 31) 9023 Result = DAG.getTargetConstant(Value, Op.getValueType()); 9024 break; 9025 case 'N': // "N" is a positive constant that is an exact power of two. 9026 if ((int)Value > 0 && isPowerOf2_32(Value)) 9027 Result = DAG.getTargetConstant(Value, Op.getValueType()); 9028 break; 9029 case 'O': // "O" is the constant zero. 9030 if (Value == 0) 9031 Result = DAG.getTargetConstant(Value, Op.getValueType()); 9032 break; 9033 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 9034 if ((short)-Value == (int)-Value) 9035 Result = DAG.getTargetConstant(Value, Op.getValueType()); 9036 break; 9037 } 9038 break; 9039 } 9040 } 9041 9042 if (Result.getNode()) { 9043 Ops.push_back(Result); 9044 return; 9045 } 9046 9047 // Handle standard constraint letters. 9048 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 9049 } 9050 9051 // isLegalAddressingMode - Return true if the addressing mode represented 9052 // by AM is legal for this target, for a load/store of the specified type. 9053 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM, 9054 Type *Ty) const { 9055 // FIXME: PPC does not allow r+i addressing modes for vectors! 9056 9057 // PPC allows a sign-extended 16-bit immediate field. 9058 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 9059 return false; 9060 9061 // No global is ever allowed as a base. 9062 if (AM.BaseGV) 9063 return false; 9064 9065 // PPC only support r+r, 9066 switch (AM.Scale) { 9067 case 0: // "r+i" or just "i", depending on HasBaseReg. 9068 break; 9069 case 1: 9070 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 9071 return false; 9072 // Otherwise we have r+r or r+i. 9073 break; 9074 case 2: 9075 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 9076 return false; 9077 // Allow 2*r as r+r. 9078 break; 9079 default: 9080 // No other scales are supported. 9081 return false; 9082 } 9083 9084 return true; 9085 } 9086 9087 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 9088 SelectionDAG &DAG) const { 9089 MachineFunction &MF = DAG.getMachineFunction(); 9090 MachineFrameInfo *MFI = MF.getFrameInfo(); 9091 MFI->setReturnAddressIsTaken(true); 9092 9093 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 9094 return SDValue(); 9095 9096 SDLoc dl(Op); 9097 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9098 9099 // Make sure the function does not optimize away the store of the RA to 9100 // the stack. 9101 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 9102 FuncInfo->setLRStoreRequired(); 9103 bool isPPC64 = Subtarget.isPPC64(); 9104 bool isDarwinABI = Subtarget.isDarwinABI(); 9105 9106 if (Depth > 0) { 9107 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 9108 SDValue Offset = 9109 9110 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI), 9111 isPPC64? MVT::i64 : MVT::i32); 9112 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 9113 DAG.getNode(ISD::ADD, dl, getPointerTy(), 9114 FrameAddr, Offset), 9115 MachinePointerInfo(), false, false, false, 0); 9116 } 9117 9118 // Just load the return address off the stack. 9119 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 9120 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 9121 RetAddrFI, MachinePointerInfo(), false, false, false, 0); 9122 } 9123 9124 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 9125 SelectionDAG &DAG) const { 9126 SDLoc dl(Op); 9127 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9128 9129 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 9130 bool isPPC64 = PtrVT == MVT::i64; 9131 9132 MachineFunction &MF = DAG.getMachineFunction(); 9133 MachineFrameInfo *MFI = MF.getFrameInfo(); 9134 MFI->setFrameAddressIsTaken(true); 9135 9136 // Naked functions never have a frame pointer, and so we use r1. For all 9137 // other functions, this decision must be delayed until during PEI. 9138 unsigned FrameReg; 9139 if (MF.getFunction()->getAttributes().hasAttribute( 9140 AttributeSet::FunctionIndex, Attribute::Naked)) 9141 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 9142 else 9143 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 9144 9145 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 9146 PtrVT); 9147 while (Depth--) 9148 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 9149 FrameAddr, MachinePointerInfo(), false, false, 9150 false, 0); 9151 return FrameAddr; 9152 } 9153 9154 // FIXME? Maybe this could be a TableGen attribute on some registers and 9155 // this table could be generated automatically from RegInfo. 9156 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, 9157 EVT VT) const { 9158 bool isPPC64 = Subtarget.isPPC64(); 9159 bool isDarwinABI = Subtarget.isDarwinABI(); 9160 9161 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 9162 (!isPPC64 && VT != MVT::i32)) 9163 report_fatal_error("Invalid register global variable type"); 9164 9165 bool is64Bit = isPPC64 && VT == MVT::i64; 9166 unsigned Reg = StringSwitch<unsigned>(RegName) 9167 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 9168 .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2)) 9169 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 9170 (is64Bit ? PPC::X13 : PPC::R13)) 9171 .Default(0); 9172 9173 if (Reg) 9174 return Reg; 9175 report_fatal_error("Invalid register name global variable"); 9176 } 9177 9178 bool 9179 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 9180 // The PowerPC target isn't yet aware of offsets. 9181 return false; 9182 } 9183 9184 /// getOptimalMemOpType - Returns the target specific optimal type for load 9185 /// and store operations as a result of memset, memcpy, and memmove 9186 /// lowering. If DstAlign is zero that means it's safe to destination 9187 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 9188 /// means there isn't a need to check it against alignment requirement, 9189 /// probably because the source does not need to be loaded. If 'IsMemset' is 9190 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 9191 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 9192 /// source is constant so it does not need to be loaded. 9193 /// It returns EVT::Other if the type should be determined using generic 9194 /// target-independent logic. 9195 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 9196 unsigned DstAlign, unsigned SrcAlign, 9197 bool IsMemset, bool ZeroMemset, 9198 bool MemcpyStrSrc, 9199 MachineFunction &MF) const { 9200 if (Subtarget.isPPC64()) { 9201 return MVT::i64; 9202 } else { 9203 return MVT::i32; 9204 } 9205 } 9206 9207 /// \brief Returns true if it is beneficial to convert a load of a constant 9208 /// to just the constant itself. 9209 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 9210 Type *Ty) const { 9211 assert(Ty->isIntegerTy()); 9212 9213 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 9214 if (BitSize == 0 || BitSize > 64) 9215 return false; 9216 return true; 9217 } 9218 9219 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 9220 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 9221 return false; 9222 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 9223 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 9224 return NumBits1 == 64 && NumBits2 == 32; 9225 } 9226 9227 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 9228 if (!VT1.isInteger() || !VT2.isInteger()) 9229 return false; 9230 unsigned NumBits1 = VT1.getSizeInBits(); 9231 unsigned NumBits2 = VT2.getSizeInBits(); 9232 return NumBits1 == 64 && NumBits2 == 32; 9233 } 9234 9235 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 9236 return isInt<16>(Imm) || isUInt<16>(Imm); 9237 } 9238 9239 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 9240 return isInt<16>(Imm) || isUInt<16>(Imm); 9241 } 9242 9243 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, 9244 unsigned, 9245 bool *Fast) const { 9246 if (DisablePPCUnaligned) 9247 return false; 9248 9249 // PowerPC supports unaligned memory access for simple non-vector types. 9250 // Although accessing unaligned addresses is not as efficient as accessing 9251 // aligned addresses, it is generally more efficient than manual expansion, 9252 // and generally only traps for software emulation when crossing page 9253 // boundaries. 9254 9255 if (!VT.isSimple()) 9256 return false; 9257 9258 if (VT.getSimpleVT().isVector()) { 9259 if (Subtarget.hasVSX()) { 9260 if (VT != MVT::v2f64 && VT != MVT::v2i64) 9261 return false; 9262 } else { 9263 return false; 9264 } 9265 } 9266 9267 if (VT == MVT::ppcf128) 9268 return false; 9269 9270 if (Fast) 9271 *Fast = true; 9272 9273 return true; 9274 } 9275 9276 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 9277 VT = VT.getScalarType(); 9278 9279 if (!VT.isSimple()) 9280 return false; 9281 9282 switch (VT.getSimpleVT().SimpleTy) { 9283 case MVT::f32: 9284 case MVT::f64: 9285 return true; 9286 default: 9287 break; 9288 } 9289 9290 return false; 9291 } 9292 9293 bool 9294 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 9295 EVT VT , unsigned DefinedValues) const { 9296 if (VT == MVT::v2i64) 9297 return false; 9298 9299 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 9300 } 9301 9302 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 9303 if (DisableILPPref || Subtarget.enableMachineScheduler()) 9304 return TargetLowering::getSchedulingPreference(N); 9305 9306 return Sched::ILP; 9307 } 9308 9309 // Create a fast isel object. 9310 FastISel * 9311 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 9312 const TargetLibraryInfo *LibInfo) const { 9313 return PPC::createFastISel(FuncInfo, LibInfo); 9314 } 9315