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/CodeGen/CallingConvLower.h" 22 #include "llvm/CodeGen/MachineFrameInfo.h" 23 #include "llvm/CodeGen/MachineFunction.h" 24 #include "llvm/CodeGen/MachineInstrBuilder.h" 25 #include "llvm/CodeGen/MachineRegisterInfo.h" 26 #include "llvm/CodeGen/SelectionDAG.h" 27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 28 #include "llvm/IR/CallingConv.h" 29 #include "llvm/IR/Constants.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/Intrinsics.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Target/TargetOptions.h" 38 using namespace llvm; 39 40 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 41 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 42 43 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 44 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 45 46 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 47 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 48 49 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) { 50 if (TM.getSubtargetImpl()->isDarwin()) 51 return new TargetLoweringObjectFileMachO(); 52 53 if (TM.getSubtargetImpl()->isSVR4ABI()) 54 return new PPC64LinuxTargetObjectFile(); 55 56 return new TargetLoweringObjectFileELF(); 57 } 58 59 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM) 60 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) { 61 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>(); 62 63 setPow2DivIsCheap(); 64 65 // Use _setjmp/_longjmp instead of setjmp/longjmp. 66 setUseUnderscoreSetJmp(true); 67 setUseUnderscoreLongJmp(true); 68 69 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 70 // arguments are at least 4/8 bytes aligned. 71 bool isPPC64 = Subtarget->isPPC64(); 72 setMinStackArgumentAlignment(isPPC64 ? 8:4); 73 74 // Set up the register classes. 75 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 76 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 77 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 78 79 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD 80 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 81 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand); 82 83 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 84 85 // PowerPC has pre-inc load and store's. 86 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 87 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 88 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 89 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 90 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 91 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 92 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 93 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 94 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 95 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 96 97 // This is used in the ppcf128->int sequence. Note it has different semantics 98 // from FP_ROUND: that rounds to nearest, this rounds to zero. 99 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); 100 101 // We do not currently implement these libm ops for PowerPC. 102 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 103 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 104 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 105 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 106 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 107 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 108 109 // PowerPC has no SREM/UREM instructions 110 setOperationAction(ISD::SREM, MVT::i32, Expand); 111 setOperationAction(ISD::UREM, MVT::i32, Expand); 112 setOperationAction(ISD::SREM, MVT::i64, Expand); 113 setOperationAction(ISD::UREM, MVT::i64, Expand); 114 115 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 116 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 117 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 118 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 119 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 120 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 121 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 122 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 123 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 124 125 // We don't support sin/cos/sqrt/fmod/pow 126 setOperationAction(ISD::FSIN , MVT::f64, Expand); 127 setOperationAction(ISD::FCOS , MVT::f64, Expand); 128 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 129 setOperationAction(ISD::FREM , MVT::f64, Expand); 130 setOperationAction(ISD::FPOW , MVT::f64, Expand); 131 setOperationAction(ISD::FMA , MVT::f64, Legal); 132 setOperationAction(ISD::FSIN , MVT::f32, Expand); 133 setOperationAction(ISD::FCOS , MVT::f32, Expand); 134 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 135 setOperationAction(ISD::FREM , MVT::f32, Expand); 136 setOperationAction(ISD::FPOW , MVT::f32, Expand); 137 setOperationAction(ISD::FMA , MVT::f32, Legal); 138 139 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 140 141 // If we're enabling GP optimizations, use hardware square root 142 if (!Subtarget->hasFSQRT() && 143 !(TM.Options.UnsafeFPMath && 144 Subtarget->hasFRSQRTE() && Subtarget->hasFRE())) 145 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 146 147 if (!Subtarget->hasFSQRT() && 148 !(TM.Options.UnsafeFPMath && 149 Subtarget->hasFRSQRTES() && Subtarget->hasFRES())) 150 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 151 152 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 153 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 154 155 if (Subtarget->hasFPRND()) { 156 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 157 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 158 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 159 160 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 161 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 162 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 163 164 // frin does not implement "ties to even." Thus, this is safe only in 165 // fast-math mode. 166 if (TM.Options.UnsafeFPMath) { 167 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 168 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 169 170 // These need to set FE_INEXACT, and use a custom inserter. 171 setOperationAction(ISD::FRINT, MVT::f64, Legal); 172 setOperationAction(ISD::FRINT, MVT::f32, Legal); 173 } 174 } 175 176 // PowerPC does not have BSWAP, CTPOP or CTTZ 177 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 178 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 179 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand); 180 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand); 181 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 182 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 183 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand); 184 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand); 185 186 if (Subtarget->hasPOPCNTD()) { 187 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 188 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 189 } else { 190 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 191 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 192 } 193 194 // PowerPC does not have ROTR 195 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 196 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 197 198 // PowerPC does not have Select 199 setOperationAction(ISD::SELECT, MVT::i32, Expand); 200 setOperationAction(ISD::SELECT, MVT::i64, Expand); 201 setOperationAction(ISD::SELECT, MVT::f32, Expand); 202 setOperationAction(ISD::SELECT, MVT::f64, Expand); 203 204 // PowerPC wants to turn select_cc of FP into fsel when possible. 205 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 206 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 207 208 // PowerPC wants to optimize integer setcc a bit 209 setOperationAction(ISD::SETCC, MVT::i32, Custom); 210 211 // PowerPC does not have BRCOND which requires SetCC 212 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 213 214 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 215 216 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 217 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 218 219 // PowerPC does not have [U|S]INT_TO_FP 220 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 221 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 222 223 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 224 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 225 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 226 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 227 228 // We cannot sextinreg(i1). Expand to shifts. 229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 230 231 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 232 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 233 // support continuation, user-level threading, and etc.. As a result, no 234 // other SjLj exception interfaces are implemented and please don't build 235 // your own exception handling based on them. 236 // LLVM/Clang supports zero-cost DWARF exception handling. 237 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 238 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 239 240 // We want to legalize GlobalAddress and ConstantPool nodes into the 241 // appropriate instructions to materialize the address. 242 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 243 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 244 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 245 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 246 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 247 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 248 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 249 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 250 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 251 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 252 253 // TRAP is legal. 254 setOperationAction(ISD::TRAP, MVT::Other, Legal); 255 256 // TRAMPOLINE is custom lowered. 257 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 258 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 259 260 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 261 setOperationAction(ISD::VASTART , MVT::Other, Custom); 262 263 if (Subtarget->isSVR4ABI()) { 264 if (isPPC64) { 265 // VAARG always uses double-word chunks, so promote anything smaller. 266 setOperationAction(ISD::VAARG, MVT::i1, Promote); 267 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 268 setOperationAction(ISD::VAARG, MVT::i8, Promote); 269 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 270 setOperationAction(ISD::VAARG, MVT::i16, Promote); 271 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 272 setOperationAction(ISD::VAARG, MVT::i32, Promote); 273 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 274 setOperationAction(ISD::VAARG, MVT::Other, Expand); 275 } else { 276 // VAARG is custom lowered with the 32-bit SVR4 ABI. 277 setOperationAction(ISD::VAARG, MVT::Other, Custom); 278 setOperationAction(ISD::VAARG, MVT::i64, Custom); 279 } 280 } else 281 setOperationAction(ISD::VAARG, MVT::Other, Expand); 282 283 if (Subtarget->isSVR4ABI() && !isPPC64) 284 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 285 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 286 else 287 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 288 289 // Use the default implementation. 290 setOperationAction(ISD::VAEND , MVT::Other, Expand); 291 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 292 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 293 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 294 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 295 296 // We want to custom lower some of our intrinsics. 297 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 298 299 // To handle counter-based loop conditions. 300 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 301 302 // Comparisons that require checking two conditions. 303 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 304 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 305 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 306 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 307 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 308 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 309 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 310 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 311 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 312 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 313 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 314 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 315 316 if (Subtarget->has64BitSupport()) { 317 // They also have instructions for converting between i64 and fp. 318 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 319 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 320 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 321 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 322 // This is just the low 32 bits of a (signed) fp->i64 conversion. 323 // We cannot do this with Promote because i64 is not a legal type. 324 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 325 326 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64()) 327 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 328 } else { 329 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 330 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 331 } 332 333 // With the instructions enabled under FPCVT, we can do everything. 334 if (PPCSubTarget.hasFPCVT()) { 335 if (Subtarget->has64BitSupport()) { 336 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 337 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 338 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 339 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 340 } 341 342 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 343 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 344 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 345 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 346 } 347 348 if (Subtarget->use64BitRegs()) { 349 // 64-bit PowerPC implementations can support i64 types directly 350 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 351 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 352 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 353 // 64-bit PowerPC wants to expand i128 shifts itself. 354 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 355 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 356 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 357 } else { 358 // 32-bit PowerPC wants to expand i64 shifts itself. 359 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 360 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 361 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 362 } 363 364 if (Subtarget->hasAltivec()) { 365 // First set operation action for all vector types to expand. Then we 366 // will selectively turn on ones that can be effectively codegen'd. 367 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 368 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) { 369 MVT::SimpleValueType VT = (MVT::SimpleValueType)i; 370 371 // add/sub are legal for all supported vector VT's. 372 setOperationAction(ISD::ADD , VT, Legal); 373 setOperationAction(ISD::SUB , VT, Legal); 374 375 // We promote all shuffles to v16i8. 376 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 377 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 378 379 // We promote all non-typed operations to v4i32. 380 setOperationAction(ISD::AND , VT, Promote); 381 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 382 setOperationAction(ISD::OR , VT, Promote); 383 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 384 setOperationAction(ISD::XOR , VT, Promote); 385 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 386 setOperationAction(ISD::LOAD , VT, Promote); 387 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 388 setOperationAction(ISD::SELECT, VT, Promote); 389 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 390 setOperationAction(ISD::STORE, VT, Promote); 391 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 392 393 // No other operations are legal. 394 setOperationAction(ISD::MUL , VT, Expand); 395 setOperationAction(ISD::SDIV, VT, Expand); 396 setOperationAction(ISD::SREM, VT, Expand); 397 setOperationAction(ISD::UDIV, VT, Expand); 398 setOperationAction(ISD::UREM, VT, Expand); 399 setOperationAction(ISD::FDIV, VT, Expand); 400 setOperationAction(ISD::FREM, VT, Expand); 401 setOperationAction(ISD::FNEG, VT, Expand); 402 setOperationAction(ISD::FSQRT, VT, Expand); 403 setOperationAction(ISD::FLOG, VT, Expand); 404 setOperationAction(ISD::FLOG10, VT, Expand); 405 setOperationAction(ISD::FLOG2, VT, Expand); 406 setOperationAction(ISD::FEXP, VT, Expand); 407 setOperationAction(ISD::FEXP2, VT, Expand); 408 setOperationAction(ISD::FSIN, VT, Expand); 409 setOperationAction(ISD::FCOS, VT, Expand); 410 setOperationAction(ISD::FABS, VT, Expand); 411 setOperationAction(ISD::FPOWI, VT, Expand); 412 setOperationAction(ISD::FFLOOR, VT, Expand); 413 setOperationAction(ISD::FCEIL, VT, Expand); 414 setOperationAction(ISD::FTRUNC, VT, Expand); 415 setOperationAction(ISD::FRINT, VT, Expand); 416 setOperationAction(ISD::FNEARBYINT, VT, Expand); 417 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 418 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 419 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 420 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 421 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 422 setOperationAction(ISD::UDIVREM, VT, Expand); 423 setOperationAction(ISD::SDIVREM, VT, Expand); 424 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 425 setOperationAction(ISD::FPOW, VT, Expand); 426 setOperationAction(ISD::CTPOP, VT, Expand); 427 setOperationAction(ISD::CTLZ, VT, Expand); 428 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand); 429 setOperationAction(ISD::CTTZ, VT, Expand); 430 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand); 431 setOperationAction(ISD::VSELECT, VT, Expand); 432 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 433 434 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 435 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) { 436 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j; 437 setTruncStoreAction(VT, InnerVT, Expand); 438 } 439 setLoadExtAction(ISD::SEXTLOAD, VT, Expand); 440 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand); 441 setLoadExtAction(ISD::EXTLOAD, VT, Expand); 442 } 443 444 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 445 // with merges, splats, etc. 446 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 447 448 setOperationAction(ISD::AND , MVT::v4i32, Legal); 449 setOperationAction(ISD::OR , MVT::v4i32, Legal); 450 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 451 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 452 setOperationAction(ISD::SELECT, MVT::v4i32, Expand); 453 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 454 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 455 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 456 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 457 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 458 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 459 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 460 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 461 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 462 463 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 464 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 465 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 466 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 467 468 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 469 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 470 471 if (TM.Options.UnsafeFPMath) { 472 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 473 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 474 } 475 476 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 477 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 478 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 479 480 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 481 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 482 483 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 484 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 485 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 486 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 487 488 // Altivec does not contain unordered floating-point compare instructions 489 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 490 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 491 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand); 492 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand); 493 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand); 494 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand); 495 496 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 497 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 498 } 499 500 if (Subtarget->has64BitSupport()) { 501 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 502 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 503 } 504 505 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand); 506 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand); 507 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 508 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 509 510 setBooleanContents(ZeroOrOneBooleanContent); 511 // Altivec instructions set fields to all zeros or all ones. 512 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 513 514 if (isPPC64) { 515 setStackPointerRegisterToSaveRestore(PPC::X1); 516 setExceptionPointerRegister(PPC::X3); 517 setExceptionSelectorRegister(PPC::X4); 518 } else { 519 setStackPointerRegisterToSaveRestore(PPC::R1); 520 setExceptionPointerRegister(PPC::R3); 521 setExceptionSelectorRegister(PPC::R4); 522 } 523 524 // We have target-specific dag combine patterns for the following nodes: 525 setTargetDAGCombine(ISD::SINT_TO_FP); 526 setTargetDAGCombine(ISD::LOAD); 527 setTargetDAGCombine(ISD::STORE); 528 setTargetDAGCombine(ISD::BR_CC); 529 setTargetDAGCombine(ISD::BSWAP); 530 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 531 532 // Use reciprocal estimates. 533 if (TM.Options.UnsafeFPMath) { 534 setTargetDAGCombine(ISD::FDIV); 535 setTargetDAGCombine(ISD::FSQRT); 536 } 537 538 // Darwin long double math library functions have $LDBL128 appended. 539 if (Subtarget->isDarwin()) { 540 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 541 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 542 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 543 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 544 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 545 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 546 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 547 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 548 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 549 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 550 } 551 552 setMinFunctionAlignment(2); 553 if (PPCSubTarget.isDarwin()) 554 setPrefFunctionAlignment(4); 555 556 if (isPPC64 && Subtarget->isJITCodeModel()) 557 // Temporary workaround for the inability of PPC64 JIT to handle jump 558 // tables. 559 setSupportJumpTables(false); 560 561 setInsertFencesForAtomic(true); 562 563 setSchedulingPreference(Sched::Hybrid); 564 565 computeRegisterProperties(); 566 567 // The Freescale cores does better with aggressive inlining of memcpy and 568 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores). 569 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc || 570 Subtarget->getDarwinDirective() == PPC::DIR_E5500) { 571 MaxStoresPerMemset = 32; 572 MaxStoresPerMemsetOptSize = 16; 573 MaxStoresPerMemcpy = 32; 574 MaxStoresPerMemcpyOptSize = 8; 575 MaxStoresPerMemmove = 32; 576 MaxStoresPerMemmoveOptSize = 8; 577 578 setPrefFunctionAlignment(4); 579 } 580 } 581 582 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 583 /// function arguments in the caller parameter area. 584 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const { 585 const TargetMachine &TM = getTargetMachine(); 586 // Darwin passes everything on 4 byte boundary. 587 if (TM.getSubtarget<PPCSubtarget>().isDarwin()) 588 return 4; 589 590 // 16byte and wider vectors are passed on 16byte boundary. 591 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 592 if (VTy->getBitWidth() >= 128) 593 return 16; 594 595 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 596 if (PPCSubTarget.isPPC64()) 597 return 8; 598 599 return 4; 600 } 601 602 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 603 switch (Opcode) { 604 default: return 0; 605 case PPCISD::FSEL: return "PPCISD::FSEL"; 606 case PPCISD::FCFID: return "PPCISD::FCFID"; 607 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 608 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 609 case PPCISD::FRE: return "PPCISD::FRE"; 610 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 611 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 612 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 613 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 614 case PPCISD::VPERM: return "PPCISD::VPERM"; 615 case PPCISD::Hi: return "PPCISD::Hi"; 616 case PPCISD::Lo: return "PPCISD::Lo"; 617 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 618 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE"; 619 case PPCISD::LOAD: return "PPCISD::LOAD"; 620 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC"; 621 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 622 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 623 case PPCISD::SRL: return "PPCISD::SRL"; 624 case PPCISD::SRA: return "PPCISD::SRA"; 625 case PPCISD::SHL: return "PPCISD::SHL"; 626 case PPCISD::CALL: return "PPCISD::CALL"; 627 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 628 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 629 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 630 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 631 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 632 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 633 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 634 case PPCISD::VCMP: return "PPCISD::VCMP"; 635 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 636 case PPCISD::LBRX: return "PPCISD::LBRX"; 637 case PPCISD::STBRX: return "PPCISD::STBRX"; 638 case PPCISD::LARX: return "PPCISD::LARX"; 639 case PPCISD::STCX: return "PPCISD::STCX"; 640 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 641 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 642 case PPCISD::BDZ: return "PPCISD::BDZ"; 643 case PPCISD::MFFS: return "PPCISD::MFFS"; 644 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 645 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 646 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 647 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 648 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA"; 649 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L"; 650 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L"; 651 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 652 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 653 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 654 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 655 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 656 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 657 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 658 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 659 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 660 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 661 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 662 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 663 case PPCISD::SC: return "PPCISD::SC"; 664 } 665 } 666 667 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const { 668 if (!VT.isVector()) 669 return MVT::i32; 670 return VT.changeVectorElementTypeToInteger(); 671 } 672 673 //===----------------------------------------------------------------------===// 674 // Node matching predicates, for use by the tblgen matching code. 675 //===----------------------------------------------------------------------===// 676 677 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 678 static bool isFloatingPointZero(SDValue Op) { 679 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 680 return CFP->getValueAPF().isZero(); 681 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 682 // Maybe this has already been legalized into the constant pool? 683 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 684 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 685 return CFP->getValueAPF().isZero(); 686 } 687 return false; 688 } 689 690 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 691 /// true if Op is undef or if it matches the specified value. 692 static bool isConstantOrUndef(int Op, int Val) { 693 return Op < 0 || Op == Val; 694 } 695 696 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 697 /// VPKUHUM instruction. 698 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) { 699 if (!isUnary) { 700 for (unsigned i = 0; i != 16; ++i) 701 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 702 return false; 703 } else { 704 for (unsigned i = 0; i != 8; ++i) 705 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) || 706 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1)) 707 return false; 708 } 709 return true; 710 } 711 712 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 713 /// VPKUWUM instruction. 714 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) { 715 if (!isUnary) { 716 for (unsigned i = 0; i != 16; i += 2) 717 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 718 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 719 return false; 720 } else { 721 for (unsigned i = 0; i != 8; i += 2) 722 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 723 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) || 724 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) || 725 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3)) 726 return false; 727 } 728 return true; 729 } 730 731 /// isVMerge - Common function, used to match vmrg* shuffles. 732 /// 733 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 734 unsigned LHSStart, unsigned RHSStart) { 735 assert(N->getValueType(0) == MVT::v16i8 && 736 "PPC only supports shuffles by bytes!"); 737 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 738 "Unsupported merge size!"); 739 740 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 741 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 742 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 743 LHSStart+j+i*UnitSize) || 744 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 745 RHSStart+j+i*UnitSize)) 746 return false; 747 } 748 return true; 749 } 750 751 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 752 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes). 753 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 754 bool isUnary) { 755 if (!isUnary) 756 return isVMerge(N, UnitSize, 8, 24); 757 return isVMerge(N, UnitSize, 8, 8); 758 } 759 760 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 761 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes). 762 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 763 bool isUnary) { 764 if (!isUnary) 765 return isVMerge(N, UnitSize, 0, 16); 766 return isVMerge(N, UnitSize, 0, 0); 767 } 768 769 770 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 771 /// amount, otherwise return -1. 772 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) { 773 assert(N->getValueType(0) == MVT::v16i8 && 774 "PPC only supports shuffles by bytes!"); 775 776 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 777 778 // Find the first non-undef value in the shuffle mask. 779 unsigned i; 780 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 781 /*search*/; 782 783 if (i == 16) return -1; // all undef. 784 785 // Otherwise, check to see if the rest of the elements are consecutively 786 // numbered from this value. 787 unsigned ShiftAmt = SVOp->getMaskElt(i); 788 if (ShiftAmt < i) return -1; 789 ShiftAmt -= i; 790 791 if (!isUnary) { 792 // Check the rest of the elements to see if they are consecutive. 793 for (++i; i != 16; ++i) 794 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 795 return -1; 796 } else { 797 // Check the rest of the elements to see if they are consecutive. 798 for (++i; i != 16; ++i) 799 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 800 return -1; 801 } 802 return ShiftAmt; 803 } 804 805 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 806 /// specifies a splat of a single element that is suitable for input to 807 /// VSPLTB/VSPLTH/VSPLTW. 808 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 809 assert(N->getValueType(0) == MVT::v16i8 && 810 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 811 812 // This is a splat operation if each element of the permute is the same, and 813 // if the value doesn't reference the second vector. 814 unsigned ElementBase = N->getMaskElt(0); 815 816 // FIXME: Handle UNDEF elements too! 817 if (ElementBase >= 16) 818 return false; 819 820 // Check that the indices are consecutive, in the case of a multi-byte element 821 // splatted with a v16i8 mask. 822 for (unsigned i = 1; i != EltSize; ++i) 823 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 824 return false; 825 826 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 827 if (N->getMaskElt(i) < 0) continue; 828 for (unsigned j = 0; j != EltSize; ++j) 829 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 830 return false; 831 } 832 return true; 833 } 834 835 /// isAllNegativeZeroVector - Returns true if all elements of build_vector 836 /// are -0.0. 837 bool PPC::isAllNegativeZeroVector(SDNode *N) { 838 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N); 839 840 APInt APVal, APUndef; 841 unsigned BitSize; 842 bool HasAnyUndefs; 843 844 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true)) 845 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 846 return CFP->getValueAPF().isNegZero(); 847 848 return false; 849 } 850 851 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 852 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 853 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) { 854 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 855 assert(isSplatShuffleMask(SVOp, EltSize)); 856 return SVOp->getMaskElt(0) / EltSize; 857 } 858 859 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 860 /// by using a vspltis[bhw] instruction of the specified element size, return 861 /// the constant being splatted. The ByteSize field indicates the number of 862 /// bytes of each element [124] -> [bhw]. 863 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 864 SDValue OpVal(0, 0); 865 866 // If ByteSize of the splat is bigger than the element size of the 867 // build_vector, then we have a case where we are checking for a splat where 868 // multiple elements of the buildvector are folded together into a single 869 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 870 unsigned EltSize = 16/N->getNumOperands(); 871 if (EltSize < ByteSize) { 872 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 873 SDValue UniquedVals[4]; 874 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 875 876 // See if all of the elements in the buildvector agree across. 877 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 878 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 879 // If the element isn't a constant, bail fully out. 880 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 881 882 883 if (UniquedVals[i&(Multiple-1)].getNode() == 0) 884 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 885 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 886 return SDValue(); // no match. 887 } 888 889 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 890 // either constant or undef values that are identical for each chunk. See 891 // if these chunks can form into a larger vspltis*. 892 893 // Check to see if all of the leading entries are either 0 or -1. If 894 // neither, then this won't fit into the immediate field. 895 bool LeadingZero = true; 896 bool LeadingOnes = true; 897 for (unsigned i = 0; i != Multiple-1; ++i) { 898 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs. 899 900 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue(); 901 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue(); 902 } 903 // Finally, check the least significant entry. 904 if (LeadingZero) { 905 if (UniquedVals[Multiple-1].getNode() == 0) 906 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef 907 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 908 if (Val < 16) 909 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4) 910 } 911 if (LeadingOnes) { 912 if (UniquedVals[Multiple-1].getNode() == 0) 913 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef 914 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 915 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 916 return DAG.getTargetConstant(Val, MVT::i32); 917 } 918 919 return SDValue(); 920 } 921 922 // Check to see if this buildvec has a single non-undef value in its elements. 923 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 924 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 925 if (OpVal.getNode() == 0) 926 OpVal = N->getOperand(i); 927 else if (OpVal != N->getOperand(i)) 928 return SDValue(); 929 } 930 931 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def. 932 933 unsigned ValSizeInBytes = EltSize; 934 uint64_t Value = 0; 935 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 936 Value = CN->getZExtValue(); 937 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 938 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 939 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 940 } 941 942 // If the splat value is larger than the element value, then we can never do 943 // this splat. The only case that we could fit the replicated bits into our 944 // immediate field for would be zero, and we prefer to use vxor for it. 945 if (ValSizeInBytes < ByteSize) return SDValue(); 946 947 // If the element value is larger than the splat value, cut it in half and 948 // check to see if the two halves are equal. Continue doing this until we 949 // get to ByteSize. This allows us to handle 0x01010101 as 0x01. 950 while (ValSizeInBytes > ByteSize) { 951 ValSizeInBytes >>= 1; 952 953 // If the top half equals the bottom half, we're still ok. 954 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) != 955 (Value & ((1 << (8*ValSizeInBytes))-1))) 956 return SDValue(); 957 } 958 959 // Properly sign extend the value. 960 int MaskVal = SignExtend32(Value, ByteSize * 8); 961 962 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 963 if (MaskVal == 0) return SDValue(); 964 965 // Finally, if this value fits in a 5 bit sext field, return it 966 if (SignExtend32<5>(MaskVal) == MaskVal) 967 return DAG.getTargetConstant(MaskVal, MVT::i32); 968 return SDValue(); 969 } 970 971 //===----------------------------------------------------------------------===// 972 // Addressing Mode Selection 973 //===----------------------------------------------------------------------===// 974 975 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 976 /// or 64-bit immediate, and if the value can be accurately represented as a 977 /// sign extension from a 16-bit value. If so, this returns true and the 978 /// immediate. 979 static bool isIntS16Immediate(SDNode *N, short &Imm) { 980 if (N->getOpcode() != ISD::Constant) 981 return false; 982 983 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue(); 984 if (N->getValueType(0) == MVT::i32) 985 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 986 else 987 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 988 } 989 static bool isIntS16Immediate(SDValue Op, short &Imm) { 990 return isIntS16Immediate(Op.getNode(), Imm); 991 } 992 993 994 /// SelectAddressRegReg - Given the specified addressed, check to see if it 995 /// can be represented as an indexed [r+r] operation. Returns false if it 996 /// can be more efficiently represented with [r+imm]. 997 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 998 SDValue &Index, 999 SelectionDAG &DAG) const { 1000 short imm = 0; 1001 if (N.getOpcode() == ISD::ADD) { 1002 if (isIntS16Immediate(N.getOperand(1), imm)) 1003 return false; // r+i 1004 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 1005 return false; // r+i 1006 1007 Base = N.getOperand(0); 1008 Index = N.getOperand(1); 1009 return true; 1010 } else if (N.getOpcode() == ISD::OR) { 1011 if (isIntS16Immediate(N.getOperand(1), imm)) 1012 return false; // r+i can fold it if we can. 1013 1014 // If this is an or of disjoint bitfields, we can codegen this as an add 1015 // (for better address arithmetic) if the LHS and RHS of the OR are provably 1016 // disjoint. 1017 APInt LHSKnownZero, LHSKnownOne; 1018 APInt RHSKnownZero, RHSKnownOne; 1019 DAG.ComputeMaskedBits(N.getOperand(0), 1020 LHSKnownZero, LHSKnownOne); 1021 1022 if (LHSKnownZero.getBoolValue()) { 1023 DAG.ComputeMaskedBits(N.getOperand(1), 1024 RHSKnownZero, RHSKnownOne); 1025 // If all of the bits are known zero on the LHS or RHS, the add won't 1026 // carry. 1027 if (~(LHSKnownZero | RHSKnownZero) == 0) { 1028 Base = N.getOperand(0); 1029 Index = N.getOperand(1); 1030 return true; 1031 } 1032 } 1033 } 1034 1035 return false; 1036 } 1037 1038 // If we happen to be doing an i64 load or store into a stack slot that has 1039 // less than a 4-byte alignment, then the frame-index elimination may need to 1040 // use an indexed load or store instruction (because the offset may not be a 1041 // multiple of 4). The extra register needed to hold the offset comes from the 1042 // register scavenger, and it is possible that the scavenger will need to use 1043 // an emergency spill slot. As a result, we need to make sure that a spill slot 1044 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 1045 // stack slot. 1046 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 1047 // FIXME: This does not handle the LWA case. 1048 if (VT != MVT::i64) 1049 return; 1050 1051 // NOTE: We'll exclude negative FIs here, which come from argument 1052 // lowering, because there are no known test cases triggering this problem 1053 // using packed structures (or similar). We can remove this exclusion if 1054 // we find such a test case. The reason why this is so test-case driven is 1055 // because this entire 'fixup' is only to prevent crashes (from the 1056 // register scavenger) on not-really-valid inputs. For example, if we have: 1057 // %a = alloca i1 1058 // %b = bitcast i1* %a to i64* 1059 // store i64* a, i64 b 1060 // then the store should really be marked as 'align 1', but is not. If it 1061 // were marked as 'align 1' then the indexed form would have been 1062 // instruction-selected initially, and the problem this 'fixup' is preventing 1063 // won't happen regardless. 1064 if (FrameIdx < 0) 1065 return; 1066 1067 MachineFunction &MF = DAG.getMachineFunction(); 1068 MachineFrameInfo *MFI = MF.getFrameInfo(); 1069 1070 unsigned Align = MFI->getObjectAlignment(FrameIdx); 1071 if (Align >= 4) 1072 return; 1073 1074 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1075 FuncInfo->setHasNonRISpills(); 1076 } 1077 1078 /// Returns true if the address N can be represented by a base register plus 1079 /// a signed 16-bit displacement [r+imm], and if it is not better 1080 /// represented as reg+reg. If Aligned is true, only accept displacements 1081 /// suitable for STD and friends, i.e. multiples of 4. 1082 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 1083 SDValue &Base, 1084 SelectionDAG &DAG, 1085 bool Aligned) const { 1086 // FIXME dl should come from parent load or store, not from address 1087 SDLoc dl(N); 1088 // If this can be more profitably realized as r+r, fail. 1089 if (SelectAddressRegReg(N, Disp, Base, DAG)) 1090 return false; 1091 1092 if (N.getOpcode() == ISD::ADD) { 1093 short imm = 0; 1094 if (isIntS16Immediate(N.getOperand(1), imm) && 1095 (!Aligned || (imm & 3) == 0)) { 1096 Disp = DAG.getTargetConstant(imm, N.getValueType()); 1097 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 1098 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1099 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1100 } else { 1101 Base = N.getOperand(0); 1102 } 1103 return true; // [r+i] 1104 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 1105 // Match LOAD (ADD (X, Lo(G))). 1106 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 1107 && "Cannot handle constant offsets yet!"); 1108 Disp = N.getOperand(1).getOperand(0); // The global address. 1109 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 1110 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 1111 Disp.getOpcode() == ISD::TargetConstantPool || 1112 Disp.getOpcode() == ISD::TargetJumpTable); 1113 Base = N.getOperand(0); 1114 return true; // [&g+r] 1115 } 1116 } else if (N.getOpcode() == ISD::OR) { 1117 short imm = 0; 1118 if (isIntS16Immediate(N.getOperand(1), imm) && 1119 (!Aligned || (imm & 3) == 0)) { 1120 // If this is an or of disjoint bitfields, we can codegen this as an add 1121 // (for better address arithmetic) if the LHS and RHS of the OR are 1122 // provably disjoint. 1123 APInt LHSKnownZero, LHSKnownOne; 1124 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne); 1125 1126 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 1127 // If all of the bits are known zero on the LHS or RHS, the add won't 1128 // carry. 1129 Base = N.getOperand(0); 1130 Disp = DAG.getTargetConstant(imm, N.getValueType()); 1131 return true; 1132 } 1133 } 1134 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 1135 // Loading from a constant address. 1136 1137 // If this address fits entirely in a 16-bit sext immediate field, codegen 1138 // this as "d, 0" 1139 short Imm; 1140 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) { 1141 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0)); 1142 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 1143 CN->getValueType(0)); 1144 return true; 1145 } 1146 1147 // Handle 32-bit sext immediates with LIS + addr mode. 1148 if ((CN->getValueType(0) == MVT::i32 || 1149 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 1150 (!Aligned || (CN->getZExtValue() & 3) == 0)) { 1151 int Addr = (int)CN->getZExtValue(); 1152 1153 // Otherwise, break this down into an LIS + disp. 1154 Disp = DAG.getTargetConstant((short)Addr, MVT::i32); 1155 1156 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32); 1157 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 1158 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 1159 return true; 1160 } 1161 } 1162 1163 Disp = DAG.getTargetConstant(0, getPointerTy()); 1164 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 1165 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1166 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1167 } else 1168 Base = N; 1169 return true; // [r+0] 1170 } 1171 1172 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 1173 /// represented as an indexed [r+r] operation. 1174 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 1175 SDValue &Index, 1176 SelectionDAG &DAG) const { 1177 // Check to see if we can easily represent this as an [r+r] address. This 1178 // will fail if it thinks that the address is more profitably represented as 1179 // reg+imm, e.g. where imm = 0. 1180 if (SelectAddressRegReg(N, Base, Index, DAG)) 1181 return true; 1182 1183 // If the operand is an addition, always emit this as [r+r], since this is 1184 // better (for code size, and execution, as the memop does the add for free) 1185 // than emitting an explicit add. 1186 if (N.getOpcode() == ISD::ADD) { 1187 Base = N.getOperand(0); 1188 Index = N.getOperand(1); 1189 return true; 1190 } 1191 1192 // Otherwise, do it the hard way, using R0 as the base register. 1193 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 1194 N.getValueType()); 1195 Index = N; 1196 return true; 1197 } 1198 1199 /// getPreIndexedAddressParts - returns true by value, base pointer and 1200 /// offset pointer and addressing mode by reference if the node's address 1201 /// can be legally represented as pre-indexed load / store address. 1202 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 1203 SDValue &Offset, 1204 ISD::MemIndexedMode &AM, 1205 SelectionDAG &DAG) const { 1206 if (DisablePPCPreinc) return false; 1207 1208 bool isLoad = true; 1209 SDValue Ptr; 1210 EVT VT; 1211 unsigned Alignment; 1212 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 1213 Ptr = LD->getBasePtr(); 1214 VT = LD->getMemoryVT(); 1215 Alignment = LD->getAlignment(); 1216 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 1217 Ptr = ST->getBasePtr(); 1218 VT = ST->getMemoryVT(); 1219 Alignment = ST->getAlignment(); 1220 isLoad = false; 1221 } else 1222 return false; 1223 1224 // PowerPC doesn't have preinc load/store instructions for vectors. 1225 if (VT.isVector()) 1226 return false; 1227 1228 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 1229 1230 // Common code will reject creating a pre-inc form if the base pointer 1231 // is a frame index, or if N is a store and the base pointer is either 1232 // the same as or a predecessor of the value being stored. Check for 1233 // those situations here, and try with swapped Base/Offset instead. 1234 bool Swap = false; 1235 1236 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 1237 Swap = true; 1238 else if (!isLoad) { 1239 SDValue Val = cast<StoreSDNode>(N)->getValue(); 1240 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 1241 Swap = true; 1242 } 1243 1244 if (Swap) 1245 std::swap(Base, Offset); 1246 1247 AM = ISD::PRE_INC; 1248 return true; 1249 } 1250 1251 // LDU/STU can only handle immediates that are a multiple of 4. 1252 if (VT != MVT::i64) { 1253 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false)) 1254 return false; 1255 } else { 1256 // LDU/STU need an address with at least 4-byte alignment. 1257 if (Alignment < 4) 1258 return false; 1259 1260 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true)) 1261 return false; 1262 } 1263 1264 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 1265 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 1266 // sext i32 to i64 when addr mode is r+i. 1267 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 1268 LD->getExtensionType() == ISD::SEXTLOAD && 1269 isa<ConstantSDNode>(Offset)) 1270 return false; 1271 } 1272 1273 AM = ISD::PRE_INC; 1274 return true; 1275 } 1276 1277 //===----------------------------------------------------------------------===// 1278 // LowerOperation implementation 1279 //===----------------------------------------------------------------------===// 1280 1281 /// GetLabelAccessInfo - Return true if we should reference labels using a 1282 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags. 1283 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags, 1284 unsigned &LoOpFlags, const GlobalValue *GV = 0) { 1285 HiOpFlags = PPCII::MO_HA; 1286 LoOpFlags = PPCII::MO_LO; 1287 1288 // Don't use the pic base if not in PIC relocation model. Or if we are on a 1289 // non-darwin platform. We don't support PIC on other platforms yet. 1290 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ && 1291 TM.getSubtarget<PPCSubtarget>().isDarwin(); 1292 if (isPIC) { 1293 HiOpFlags |= PPCII::MO_PIC_FLAG; 1294 LoOpFlags |= PPCII::MO_PIC_FLAG; 1295 } 1296 1297 // If this is a reference to a global value that requires a non-lazy-ptr, make 1298 // sure that instruction lowering adds it. 1299 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) { 1300 HiOpFlags |= PPCII::MO_NLP_FLAG; 1301 LoOpFlags |= PPCII::MO_NLP_FLAG; 1302 1303 if (GV->hasHiddenVisibility()) { 1304 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 1305 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 1306 } 1307 } 1308 1309 return isPIC; 1310 } 1311 1312 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 1313 SelectionDAG &DAG) { 1314 EVT PtrVT = HiPart.getValueType(); 1315 SDValue Zero = DAG.getConstant(0, PtrVT); 1316 SDLoc DL(HiPart); 1317 1318 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 1319 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 1320 1321 // With PIC, the first instruction is actually "GR+hi(&G)". 1322 if (isPIC) 1323 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 1324 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 1325 1326 // Generate non-pic code that has direct accesses to the constant pool. 1327 // The address of the global is just (hi(&g)+lo(&g)). 1328 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 1329 } 1330 1331 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 1332 SelectionDAG &DAG) const { 1333 EVT PtrVT = Op.getValueType(); 1334 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 1335 const Constant *C = CP->getConstVal(); 1336 1337 // 64-bit SVR4 ABI code is always position-independent. 1338 // The actual address of the GlobalValue is stored in the TOC. 1339 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) { 1340 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 1341 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA, 1342 DAG.getRegister(PPC::X2, MVT::i64)); 1343 } 1344 1345 unsigned MOHiFlag, MOLoFlag; 1346 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag); 1347 SDValue CPIHi = 1348 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 1349 SDValue CPILo = 1350 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 1351 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG); 1352 } 1353 1354 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 1355 EVT PtrVT = Op.getValueType(); 1356 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 1357 1358 // 64-bit SVR4 ABI code is always position-independent. 1359 // The actual address of the GlobalValue is stored in the TOC. 1360 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) { 1361 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 1362 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA, 1363 DAG.getRegister(PPC::X2, MVT::i64)); 1364 } 1365 1366 unsigned MOHiFlag, MOLoFlag; 1367 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag); 1368 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 1369 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 1370 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG); 1371 } 1372 1373 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 1374 SelectionDAG &DAG) const { 1375 EVT PtrVT = Op.getValueType(); 1376 1377 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 1378 1379 unsigned MOHiFlag, MOLoFlag; 1380 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag); 1381 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 1382 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 1383 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG); 1384 } 1385 1386 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 1387 SelectionDAG &DAG) const { 1388 1389 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 1390 SDLoc dl(GA); 1391 const GlobalValue *GV = GA->getGlobal(); 1392 EVT PtrVT = getPointerTy(); 1393 bool is64bit = PPCSubTarget.isPPC64(); 1394 1395 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 1396 1397 if (Model == TLSModel::LocalExec) { 1398 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1399 PPCII::MO_TPREL_HA); 1400 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1401 PPCII::MO_TPREL_LO); 1402 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2, 1403 is64bit ? MVT::i64 : MVT::i32); 1404 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 1405 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 1406 } 1407 1408 if (!is64bit) 1409 llvm_unreachable("only local-exec is currently supported for ppc32"); 1410 1411 if (Model == TLSModel::InitialExec) { 1412 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 1413 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1414 PPCII::MO_TLS); 1415 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 1416 SDValue TPOffsetHi = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 1417 PtrVT, GOTReg, TGA); 1418 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 1419 PtrVT, TGA, TPOffsetHi); 1420 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 1421 } 1422 1423 if (Model == TLSModel::GeneralDynamic) { 1424 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 1425 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 1426 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 1427 GOTReg, TGA); 1428 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT, 1429 GOTEntryHi, TGA); 1430 1431 // We need a chain node, and don't have one handy. The underlying 1432 // call has no side effects, so using the function entry node 1433 // suffices. 1434 SDValue Chain = DAG.getEntryNode(); 1435 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry); 1436 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64); 1437 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl, 1438 PtrVT, ParmReg, TGA); 1439 // The return value from GET_TLS_ADDR really is in X3 already, but 1440 // some hacks are needed here to tie everything together. The extra 1441 // copies dissolve during subsequent transforms. 1442 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr); 1443 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT); 1444 } 1445 1446 if (Model == TLSModel::LocalDynamic) { 1447 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 1448 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 1449 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 1450 GOTReg, TGA); 1451 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT, 1452 GOTEntryHi, TGA); 1453 1454 // We need a chain node, and don't have one handy. The underlying 1455 // call has no side effects, so using the function entry node 1456 // suffices. 1457 SDValue Chain = DAG.getEntryNode(); 1458 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry); 1459 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64); 1460 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl, 1461 PtrVT, ParmReg, TGA); 1462 // The return value from GET_TLSLD_ADDR really is in X3 already, but 1463 // some hacks are needed here to tie everything together. The extra 1464 // copies dissolve during subsequent transforms. 1465 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr); 1466 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT, 1467 Chain, ParmReg, TGA); 1468 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 1469 } 1470 1471 llvm_unreachable("Unknown TLS model!"); 1472 } 1473 1474 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 1475 SelectionDAG &DAG) const { 1476 EVT PtrVT = Op.getValueType(); 1477 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 1478 SDLoc DL(GSDN); 1479 const GlobalValue *GV = GSDN->getGlobal(); 1480 1481 // 64-bit SVR4 ABI code is always position-independent. 1482 // The actual address of the GlobalValue is stored in the TOC. 1483 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) { 1484 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 1485 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA, 1486 DAG.getRegister(PPC::X2, MVT::i64)); 1487 } 1488 1489 unsigned MOHiFlag, MOLoFlag; 1490 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV); 1491 1492 SDValue GAHi = 1493 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 1494 SDValue GALo = 1495 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 1496 1497 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG); 1498 1499 // If the global reference is actually to a non-lazy-pointer, we have to do an 1500 // extra load to get the address of the global. 1501 if (MOHiFlag & PPCII::MO_NLP_FLAG) 1502 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(), 1503 false, false, false, 0); 1504 return Ptr; 1505 } 1506 1507 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 1508 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1509 SDLoc dl(Op); 1510 1511 // If we're comparing for equality to zero, expose the fact that this is 1512 // implented as a ctlz/srl pair on ppc, so that the dag combiner can 1513 // fold the new nodes. 1514 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1515 if (C->isNullValue() && CC == ISD::SETEQ) { 1516 EVT VT = Op.getOperand(0).getValueType(); 1517 SDValue Zext = Op.getOperand(0); 1518 if (VT.bitsLT(MVT::i32)) { 1519 VT = MVT::i32; 1520 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 1521 } 1522 unsigned Log2b = Log2_32(VT.getSizeInBits()); 1523 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 1524 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 1525 DAG.getConstant(Log2b, MVT::i32)); 1526 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 1527 } 1528 // Leave comparisons against 0 and -1 alone for now, since they're usually 1529 // optimized. FIXME: revisit this when we can custom lower all setcc 1530 // optimizations. 1531 if (C->isAllOnesValue() || C->isNullValue()) 1532 return SDValue(); 1533 } 1534 1535 // If we have an integer seteq/setne, turn it into a compare against zero 1536 // by xor'ing the rhs with the lhs, which is faster than setting a 1537 // condition register, reading it back out, and masking the correct bit. The 1538 // normal approach here uses sub to do this instead of xor. Using xor exposes 1539 // the result to other bit-twiddling opportunities. 1540 EVT LHSVT = Op.getOperand(0).getValueType(); 1541 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1542 EVT VT = Op.getValueType(); 1543 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 1544 Op.getOperand(1)); 1545 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC); 1546 } 1547 return SDValue(); 1548 } 1549 1550 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG, 1551 const PPCSubtarget &Subtarget) const { 1552 SDNode *Node = Op.getNode(); 1553 EVT VT = Node->getValueType(0); 1554 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1555 SDValue InChain = Node->getOperand(0); 1556 SDValue VAListPtr = Node->getOperand(1); 1557 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 1558 SDLoc dl(Node); 1559 1560 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 1561 1562 // gpr_index 1563 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 1564 VAListPtr, MachinePointerInfo(SV), MVT::i8, 1565 false, false, 0); 1566 InChain = GprIndex.getValue(1); 1567 1568 if (VT == MVT::i64) { 1569 // Check if GprIndex is even 1570 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 1571 DAG.getConstant(1, MVT::i32)); 1572 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 1573 DAG.getConstant(0, MVT::i32), ISD::SETNE); 1574 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 1575 DAG.getConstant(1, MVT::i32)); 1576 // Align GprIndex to be even if it isn't 1577 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 1578 GprIndex); 1579 } 1580 1581 // fpr index is 1 byte after gpr 1582 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 1583 DAG.getConstant(1, MVT::i32)); 1584 1585 // fpr 1586 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 1587 FprPtr, MachinePointerInfo(SV), MVT::i8, 1588 false, false, 0); 1589 InChain = FprIndex.getValue(1); 1590 1591 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 1592 DAG.getConstant(8, MVT::i32)); 1593 1594 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 1595 DAG.getConstant(4, MVT::i32)); 1596 1597 // areas 1598 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, 1599 MachinePointerInfo(), false, false, 1600 false, 0); 1601 InChain = OverflowArea.getValue(1); 1602 1603 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, 1604 MachinePointerInfo(), false, false, 1605 false, 0); 1606 InChain = RegSaveArea.getValue(1); 1607 1608 // select overflow_area if index > 8 1609 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 1610 DAG.getConstant(8, MVT::i32), ISD::SETLT); 1611 1612 // adjustment constant gpr_index * 4/8 1613 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 1614 VT.isInteger() ? GprIndex : FprIndex, 1615 DAG.getConstant(VT.isInteger() ? 4 : 8, 1616 MVT::i32)); 1617 1618 // OurReg = RegSaveArea + RegConstant 1619 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 1620 RegConstant); 1621 1622 // Floating types are 32 bytes into RegSaveArea 1623 if (VT.isFloatingPoint()) 1624 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 1625 DAG.getConstant(32, MVT::i32)); 1626 1627 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 1628 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 1629 VT.isInteger() ? GprIndex : FprIndex, 1630 DAG.getConstant(VT == MVT::i64 ? 2 : 1, 1631 MVT::i32)); 1632 1633 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 1634 VT.isInteger() ? VAListPtr : FprPtr, 1635 MachinePointerInfo(SV), 1636 MVT::i8, false, false, 0); 1637 1638 // determine if we should load from reg_save_area or overflow_area 1639 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 1640 1641 // increase overflow_area by 4/8 if gpr/fpr > 8 1642 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 1643 DAG.getConstant(VT.isInteger() ? 4 : 8, 1644 MVT::i32)); 1645 1646 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 1647 OverflowAreaPlusN); 1648 1649 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, 1650 OverflowAreaPtr, 1651 MachinePointerInfo(), 1652 MVT::i32, false, false, 0); 1653 1654 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(), 1655 false, false, false, 0); 1656 } 1657 1658 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG, 1659 const PPCSubtarget &Subtarget) const { 1660 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 1661 1662 // We have to copy the entire va_list struct: 1663 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 1664 return DAG.getMemcpy(Op.getOperand(0), Op, 1665 Op.getOperand(1), Op.getOperand(2), 1666 DAG.getConstant(12, MVT::i32), 8, false, true, 1667 MachinePointerInfo(), MachinePointerInfo()); 1668 } 1669 1670 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 1671 SelectionDAG &DAG) const { 1672 return Op.getOperand(0); 1673 } 1674 1675 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 1676 SelectionDAG &DAG) const { 1677 SDValue Chain = Op.getOperand(0); 1678 SDValue Trmp = Op.getOperand(1); // trampoline 1679 SDValue FPtr = Op.getOperand(2); // nested function 1680 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 1681 SDLoc dl(Op); 1682 1683 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1684 bool isPPC64 = (PtrVT == MVT::i64); 1685 Type *IntPtrTy = 1686 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType( 1687 *DAG.getContext()); 1688 1689 TargetLowering::ArgListTy Args; 1690 TargetLowering::ArgListEntry Entry; 1691 1692 Entry.Ty = IntPtrTy; 1693 Entry.Node = Trmp; Args.push_back(Entry); 1694 1695 // TrampSize == (isPPC64 ? 48 : 40); 1696 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, 1697 isPPC64 ? MVT::i64 : MVT::i32); 1698 Args.push_back(Entry); 1699 1700 Entry.Node = FPtr; Args.push_back(Entry); 1701 Entry.Node = Nest; Args.push_back(Entry); 1702 1703 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 1704 TargetLowering::CallLoweringInfo CLI(Chain, 1705 Type::getVoidTy(*DAG.getContext()), 1706 false, false, false, false, 0, 1707 CallingConv::C, 1708 /*isTailCall=*/false, 1709 /*doesNotRet=*/false, 1710 /*isReturnValueUsed=*/true, 1711 DAG.getExternalSymbol("__trampoline_setup", PtrVT), 1712 Args, DAG, dl); 1713 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 1714 1715 return CallResult.second; 1716 } 1717 1718 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG, 1719 const PPCSubtarget &Subtarget) const { 1720 MachineFunction &MF = DAG.getMachineFunction(); 1721 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1722 1723 SDLoc dl(Op); 1724 1725 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 1726 // vastart just stores the address of the VarArgsFrameIndex slot into the 1727 // memory location argument. 1728 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1729 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 1730 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 1731 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 1732 MachinePointerInfo(SV), 1733 false, false, 0); 1734 } 1735 1736 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 1737 // We suppose the given va_list is already allocated. 1738 // 1739 // typedef struct { 1740 // char gpr; /* index into the array of 8 GPRs 1741 // * stored in the register save area 1742 // * gpr=0 corresponds to r3, 1743 // * gpr=1 to r4, etc. 1744 // */ 1745 // char fpr; /* index into the array of 8 FPRs 1746 // * stored in the register save area 1747 // * fpr=0 corresponds to f1, 1748 // * fpr=1 to f2, etc. 1749 // */ 1750 // char *overflow_arg_area; 1751 // /* location on stack that holds 1752 // * the next overflow argument 1753 // */ 1754 // char *reg_save_area; 1755 // /* where r3:r10 and f1:f8 (if saved) 1756 // * are stored 1757 // */ 1758 // } va_list[1]; 1759 1760 1761 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32); 1762 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32); 1763 1764 1765 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1766 1767 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 1768 PtrVT); 1769 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 1770 PtrVT); 1771 1772 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 1773 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT); 1774 1775 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 1776 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT); 1777 1778 uint64_t FPROffset = 1; 1779 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT); 1780 1781 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 1782 1783 // Store first byte : number of int regs 1784 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, 1785 Op.getOperand(1), 1786 MachinePointerInfo(SV), 1787 MVT::i8, false, false, 0); 1788 uint64_t nextOffset = FPROffset; 1789 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 1790 ConstFPROffset); 1791 1792 // Store second byte : number of float regs 1793 SDValue secondStore = 1794 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 1795 MachinePointerInfo(SV, nextOffset), MVT::i8, 1796 false, false, 0); 1797 nextOffset += StackOffset; 1798 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 1799 1800 // Store second word : arguments given on stack 1801 SDValue thirdStore = 1802 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 1803 MachinePointerInfo(SV, nextOffset), 1804 false, false, 0); 1805 nextOffset += FrameOffset; 1806 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 1807 1808 // Store third word : arguments given in registers 1809 return DAG.getStore(thirdStore, dl, FR, nextPtr, 1810 MachinePointerInfo(SV, nextOffset), 1811 false, false, 0); 1812 1813 } 1814 1815 #include "PPCGenCallingConv.inc" 1816 1817 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 1818 CCValAssign::LocInfo &LocInfo, 1819 ISD::ArgFlagsTy &ArgFlags, 1820 CCState &State) { 1821 return true; 1822 } 1823 1824 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 1825 MVT &LocVT, 1826 CCValAssign::LocInfo &LocInfo, 1827 ISD::ArgFlagsTy &ArgFlags, 1828 CCState &State) { 1829 static const uint16_t ArgRegs[] = { 1830 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 1831 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 1832 }; 1833 const unsigned NumArgRegs = array_lengthof(ArgRegs); 1834 1835 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs); 1836 1837 // Skip one register if the first unallocated register has an even register 1838 // number and there are still argument registers available which have not been 1839 // allocated yet. RegNum is actually an index into ArgRegs, which means we 1840 // need to skip a register if RegNum is odd. 1841 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 1842 State.AllocateReg(ArgRegs[RegNum]); 1843 } 1844 1845 // Always return false here, as this function only makes sure that the first 1846 // unallocated register has an odd register number and does not actually 1847 // allocate a register for the current argument. 1848 return false; 1849 } 1850 1851 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 1852 MVT &LocVT, 1853 CCValAssign::LocInfo &LocInfo, 1854 ISD::ArgFlagsTy &ArgFlags, 1855 CCState &State) { 1856 static const uint16_t ArgRegs[] = { 1857 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 1858 PPC::F8 1859 }; 1860 1861 const unsigned NumArgRegs = array_lengthof(ArgRegs); 1862 1863 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs); 1864 1865 // If there is only one Floating-point register left we need to put both f64 1866 // values of a split ppc_fp128 value on the stack. 1867 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 1868 State.AllocateReg(ArgRegs[RegNum]); 1869 } 1870 1871 // Always return false here, as this function only makes sure that the two f64 1872 // values a ppc_fp128 value is split into are both passed in registers or both 1873 // passed on the stack and does not actually allocate a register for the 1874 // current argument. 1875 return false; 1876 } 1877 1878 /// GetFPR - Get the set of FP registers that should be allocated for arguments, 1879 /// on Darwin. 1880 static const uint16_t *GetFPR() { 1881 static const uint16_t FPR[] = { 1882 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 1883 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13 1884 }; 1885 1886 return FPR; 1887 } 1888 1889 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 1890 /// the stack. 1891 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 1892 unsigned PtrByteSize) { 1893 unsigned ArgSize = ArgVT.getSizeInBits()/8; 1894 if (Flags.isByVal()) 1895 ArgSize = Flags.getByValSize(); 1896 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 1897 1898 return ArgSize; 1899 } 1900 1901 SDValue 1902 PPCTargetLowering::LowerFormalArguments(SDValue Chain, 1903 CallingConv::ID CallConv, bool isVarArg, 1904 const SmallVectorImpl<ISD::InputArg> 1905 &Ins, 1906 SDLoc dl, SelectionDAG &DAG, 1907 SmallVectorImpl<SDValue> &InVals) 1908 const { 1909 if (PPCSubTarget.isSVR4ABI()) { 1910 if (PPCSubTarget.isPPC64()) 1911 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 1912 dl, DAG, InVals); 1913 else 1914 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 1915 dl, DAG, InVals); 1916 } else { 1917 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 1918 dl, DAG, InVals); 1919 } 1920 } 1921 1922 SDValue 1923 PPCTargetLowering::LowerFormalArguments_32SVR4( 1924 SDValue Chain, 1925 CallingConv::ID CallConv, bool isVarArg, 1926 const SmallVectorImpl<ISD::InputArg> 1927 &Ins, 1928 SDLoc dl, SelectionDAG &DAG, 1929 SmallVectorImpl<SDValue> &InVals) const { 1930 1931 // 32-bit SVR4 ABI Stack Frame Layout: 1932 // +-----------------------------------+ 1933 // +--> | Back chain | 1934 // | +-----------------------------------+ 1935 // | | Floating-point register save area | 1936 // | +-----------------------------------+ 1937 // | | General register save area | 1938 // | +-----------------------------------+ 1939 // | | CR save word | 1940 // | +-----------------------------------+ 1941 // | | VRSAVE save word | 1942 // | +-----------------------------------+ 1943 // | | Alignment padding | 1944 // | +-----------------------------------+ 1945 // | | Vector register save area | 1946 // | +-----------------------------------+ 1947 // | | Local variable space | 1948 // | +-----------------------------------+ 1949 // | | Parameter list area | 1950 // | +-----------------------------------+ 1951 // | | LR save word | 1952 // | +-----------------------------------+ 1953 // SP--> +--- | Back chain | 1954 // +-----------------------------------+ 1955 // 1956 // Specifications: 1957 // System V Application Binary Interface PowerPC Processor Supplement 1958 // AltiVec Technology Programming Interface Manual 1959 1960 MachineFunction &MF = DAG.getMachineFunction(); 1961 MachineFrameInfo *MFI = MF.getFrameInfo(); 1962 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1963 1964 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1965 // Potential tail calls could cause overwriting of argument stack slots. 1966 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 1967 (CallConv == CallingConv::Fast)); 1968 unsigned PtrByteSize = 4; 1969 1970 // Assign locations to all of the incoming arguments. 1971 SmallVector<CCValAssign, 16> ArgLocs; 1972 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1973 getTargetMachine(), ArgLocs, *DAG.getContext()); 1974 1975 // Reserve space for the linkage area on the stack. 1976 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize); 1977 1978 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 1979 1980 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1981 CCValAssign &VA = ArgLocs[i]; 1982 1983 // Arguments stored in registers. 1984 if (VA.isRegLoc()) { 1985 const TargetRegisterClass *RC; 1986 EVT ValVT = VA.getValVT(); 1987 1988 switch (ValVT.getSimpleVT().SimpleTy) { 1989 default: 1990 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 1991 case MVT::i32: 1992 RC = &PPC::GPRCRegClass; 1993 break; 1994 case MVT::f32: 1995 RC = &PPC::F4RCRegClass; 1996 break; 1997 case MVT::f64: 1998 RC = &PPC::F8RCRegClass; 1999 break; 2000 case MVT::v16i8: 2001 case MVT::v8i16: 2002 case MVT::v4i32: 2003 case MVT::v4f32: 2004 RC = &PPC::VRRCRegClass; 2005 break; 2006 } 2007 2008 // Transform the arguments stored in physical registers into virtual ones. 2009 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2010 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT); 2011 2012 InVals.push_back(ArgValue); 2013 } else { 2014 // Argument stored in memory. 2015 assert(VA.isMemLoc()); 2016 2017 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8; 2018 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(), 2019 isImmutable); 2020 2021 // Create load nodes to retrieve arguments from the stack. 2022 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2023 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 2024 MachinePointerInfo(), 2025 false, false, false, 0)); 2026 } 2027 } 2028 2029 // Assign locations to all of the incoming aggregate by value arguments. 2030 // Aggregates passed by value are stored in the local variable space of the 2031 // caller's stack frame, right above the parameter list area. 2032 SmallVector<CCValAssign, 16> ByValArgLocs; 2033 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 2034 getTargetMachine(), ByValArgLocs, *DAG.getContext()); 2035 2036 // Reserve stack space for the allocations in CCInfo. 2037 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 2038 2039 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 2040 2041 // Area that is at least reserved in the caller of this function. 2042 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 2043 2044 // Set the size that is at least reserved in caller of this function. Tail 2045 // call optimized function's reserved stack space needs to be aligned so that 2046 // taking the difference between two stack areas will result in an aligned 2047 // stack. 2048 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 2049 2050 MinReservedArea = 2051 std::max(MinReservedArea, 2052 PPCFrameLowering::getMinCallFrameSize(false, false)); 2053 2054 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()-> 2055 getStackAlignment(); 2056 unsigned AlignMask = TargetAlign-1; 2057 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask; 2058 2059 FI->setMinReservedArea(MinReservedArea); 2060 2061 SmallVector<SDValue, 8> MemOps; 2062 2063 // If the function takes variable number of arguments, make a frame index for 2064 // the start of the first vararg value... for expansion of llvm.va_start. 2065 if (isVarArg) { 2066 static const uint16_t GPArgRegs[] = { 2067 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2068 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2069 }; 2070 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 2071 2072 static const uint16_t FPArgRegs[] = { 2073 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 2074 PPC::F8 2075 }; 2076 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 2077 2078 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs, 2079 NumGPArgRegs)); 2080 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs, 2081 NumFPArgRegs)); 2082 2083 // Make room for NumGPArgRegs and NumFPArgRegs. 2084 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 2085 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8; 2086 2087 FuncInfo->setVarArgsStackOffset( 2088 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8, 2089 CCInfo.getNextStackOffset(), true)); 2090 2091 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false)); 2092 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2093 2094 // The fixed integer arguments of a variadic function are stored to the 2095 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing 2096 // the result of va_next. 2097 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 2098 // Get an existing live-in vreg, or add a new one. 2099 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 2100 if (!VReg) 2101 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 2102 2103 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2104 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2105 MachinePointerInfo(), false, false, 0); 2106 MemOps.push_back(Store); 2107 // Increment the address by four for the next argument to store 2108 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT); 2109 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 2110 } 2111 2112 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 2113 // is set. 2114 // The double arguments are stored to the VarArgsFrameIndex 2115 // on the stack. 2116 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 2117 // Get an existing live-in vreg, or add a new one. 2118 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 2119 if (!VReg) 2120 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 2121 2122 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 2123 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2124 MachinePointerInfo(), false, false, 0); 2125 MemOps.push_back(Store); 2126 // Increment the address by eight for the next argument to store 2127 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8, 2128 PtrVT); 2129 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 2130 } 2131 } 2132 2133 if (!MemOps.empty()) 2134 Chain = DAG.getNode(ISD::TokenFactor, dl, 2135 MVT::Other, &MemOps[0], MemOps.size()); 2136 2137 return Chain; 2138 } 2139 2140 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 2141 // value to MVT::i64 and then truncate to the correct register size. 2142 SDValue 2143 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT, 2144 SelectionDAG &DAG, SDValue ArgVal, 2145 SDLoc dl) const { 2146 if (Flags.isSExt()) 2147 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 2148 DAG.getValueType(ObjectVT)); 2149 else if (Flags.isZExt()) 2150 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 2151 DAG.getValueType(ObjectVT)); 2152 2153 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 2154 } 2155 2156 // Set the size that is at least reserved in caller of this function. Tail 2157 // call optimized functions' reserved stack space needs to be aligned so that 2158 // taking the difference between two stack areas will result in an aligned 2159 // stack. 2160 void 2161 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG, 2162 unsigned nAltivecParamsAtEnd, 2163 unsigned MinReservedArea, 2164 bool isPPC64) const { 2165 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 2166 // Add the Altivec parameters at the end, if needed. 2167 if (nAltivecParamsAtEnd) { 2168 MinReservedArea = ((MinReservedArea+15)/16)*16; 2169 MinReservedArea += 16*nAltivecParamsAtEnd; 2170 } 2171 MinReservedArea = 2172 std::max(MinReservedArea, 2173 PPCFrameLowering::getMinCallFrameSize(isPPC64, true)); 2174 unsigned TargetAlign 2175 = DAG.getMachineFunction().getTarget().getFrameLowering()-> 2176 getStackAlignment(); 2177 unsigned AlignMask = TargetAlign-1; 2178 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask; 2179 FI->setMinReservedArea(MinReservedArea); 2180 } 2181 2182 SDValue 2183 PPCTargetLowering::LowerFormalArguments_64SVR4( 2184 SDValue Chain, 2185 CallingConv::ID CallConv, bool isVarArg, 2186 const SmallVectorImpl<ISD::InputArg> 2187 &Ins, 2188 SDLoc dl, SelectionDAG &DAG, 2189 SmallVectorImpl<SDValue> &InVals) const { 2190 // TODO: add description of PPC stack frame format, or at least some docs. 2191 // 2192 MachineFunction &MF = DAG.getMachineFunction(); 2193 MachineFrameInfo *MFI = MF.getFrameInfo(); 2194 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2195 2196 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2197 // Potential tail calls could cause overwriting of argument stack slots. 2198 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 2199 (CallConv == CallingConv::Fast)); 2200 unsigned PtrByteSize = 8; 2201 2202 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true); 2203 // Area that is at least reserved in caller of this function. 2204 unsigned MinReservedArea = ArgOffset; 2205 2206 static const uint16_t GPR[] = { 2207 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 2208 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 2209 }; 2210 2211 static const uint16_t *FPR = GetFPR(); 2212 2213 static const uint16_t VR[] = { 2214 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 2215 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 2216 }; 2217 2218 const unsigned Num_GPR_Regs = array_lengthof(GPR); 2219 const unsigned Num_FPR_Regs = 13; 2220 const unsigned Num_VR_Regs = array_lengthof(VR); 2221 2222 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 2223 2224 // Add DAG nodes to load the arguments or copy them out of registers. On 2225 // entry to a function on PPC, the arguments start after the linkage area, 2226 // although the first ones are often in registers. 2227 2228 SmallVector<SDValue, 8> MemOps; 2229 unsigned nAltivecParamsAtEnd = 0; 2230 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 2231 unsigned CurArgIdx = 0; 2232 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 2233 SDValue ArgVal; 2234 bool needsLoad = false; 2235 EVT ObjectVT = Ins[ArgNo].VT; 2236 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 2237 unsigned ArgSize = ObjSize; 2238 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 2239 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx); 2240 CurArgIdx = Ins[ArgNo].OrigArgIndex; 2241 2242 unsigned CurArgOffset = ArgOffset; 2243 2244 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 2245 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 2246 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 2247 if (isVarArg) { 2248 MinReservedArea = ((MinReservedArea+15)/16)*16; 2249 MinReservedArea += CalculateStackSlotSize(ObjectVT, 2250 Flags, 2251 PtrByteSize); 2252 } else 2253 nAltivecParamsAtEnd++; 2254 } else 2255 // Calculate min reserved area. 2256 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 2257 Flags, 2258 PtrByteSize); 2259 2260 // FIXME the codegen can be much improved in some cases. 2261 // We do not have to keep everything in memory. 2262 if (Flags.isByVal()) { 2263 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 2264 ObjSize = Flags.getByValSize(); 2265 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2266 // Empty aggregate parameters do not take up registers. Examples: 2267 // struct { } a; 2268 // union { } b; 2269 // int c[0]; 2270 // etc. However, we have to provide a place-holder in InVals, so 2271 // pretend we have an 8-byte item at the current address for that 2272 // purpose. 2273 if (!ObjSize) { 2274 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); 2275 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2276 InVals.push_back(FIN); 2277 continue; 2278 } 2279 // All aggregates smaller than 8 bytes must be passed right-justified. 2280 if (ObjSize < PtrByteSize) 2281 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize); 2282 // The value of the object is its address. 2283 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true); 2284 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2285 InVals.push_back(FIN); 2286 2287 if (ObjSize < 8) { 2288 if (GPR_idx != Num_GPR_Regs) { 2289 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2290 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2291 SDValue Store; 2292 2293 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 2294 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 2295 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 2296 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 2297 MachinePointerInfo(FuncArg, CurArgOffset), 2298 ObjType, false, false, 0); 2299 } else { 2300 // For sizes that don't fit a truncating store (3, 5, 6, 7), 2301 // store the whole register as-is to the parameter save area 2302 // slot. The address of the parameter was already calculated 2303 // above (InVals.push_back(FIN)) to be the right-justified 2304 // offset within the slot. For this store, we need a new 2305 // frame index that points at the beginning of the slot. 2306 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); 2307 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2308 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2309 MachinePointerInfo(FuncArg, ArgOffset), 2310 false, false, 0); 2311 } 2312 2313 MemOps.push_back(Store); 2314 ++GPR_idx; 2315 } 2316 // Whether we copied from a register or not, advance the offset 2317 // into the parameter save area by a full doubleword. 2318 ArgOffset += PtrByteSize; 2319 continue; 2320 } 2321 2322 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 2323 // Store whatever pieces of the object are in registers 2324 // to memory. ArgOffset will be the address of the beginning 2325 // of the object. 2326 if (GPR_idx != Num_GPR_Regs) { 2327 unsigned VReg; 2328 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2329 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); 2330 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2331 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2332 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2333 MachinePointerInfo(FuncArg, ArgOffset), 2334 false, false, 0); 2335 MemOps.push_back(Store); 2336 ++GPR_idx; 2337 ArgOffset += PtrByteSize; 2338 } else { 2339 ArgOffset += ArgSize - j; 2340 break; 2341 } 2342 } 2343 continue; 2344 } 2345 2346 switch (ObjectVT.getSimpleVT().SimpleTy) { 2347 default: llvm_unreachable("Unhandled argument type!"); 2348 case MVT::i32: 2349 case MVT::i64: 2350 if (GPR_idx != Num_GPR_Regs) { 2351 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2352 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 2353 2354 if (ObjectVT == MVT::i32) 2355 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 2356 // value to MVT::i64 and then truncate to the correct register size. 2357 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 2358 2359 ++GPR_idx; 2360 } else { 2361 needsLoad = true; 2362 ArgSize = PtrByteSize; 2363 } 2364 ArgOffset += 8; 2365 break; 2366 2367 case MVT::f32: 2368 case MVT::f64: 2369 // Every 8 bytes of argument space consumes one of the GPRs available for 2370 // argument passing. 2371 if (GPR_idx != Num_GPR_Regs) { 2372 ++GPR_idx; 2373 } 2374 if (FPR_idx != Num_FPR_Regs) { 2375 unsigned VReg; 2376 2377 if (ObjectVT == MVT::f32) 2378 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 2379 else 2380 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 2381 2382 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 2383 ++FPR_idx; 2384 } else { 2385 needsLoad = true; 2386 ArgSize = PtrByteSize; 2387 } 2388 2389 ArgOffset += 8; 2390 break; 2391 case MVT::v4f32: 2392 case MVT::v4i32: 2393 case MVT::v8i16: 2394 case MVT::v16i8: 2395 // Note that vector arguments in registers don't reserve stack space, 2396 // except in varargs functions. 2397 if (VR_idx != Num_VR_Regs) { 2398 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 2399 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 2400 if (isVarArg) { 2401 while ((ArgOffset % 16) != 0) { 2402 ArgOffset += PtrByteSize; 2403 if (GPR_idx != Num_GPR_Regs) 2404 GPR_idx++; 2405 } 2406 ArgOffset += 16; 2407 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 2408 } 2409 ++VR_idx; 2410 } else { 2411 // Vectors are aligned. 2412 ArgOffset = ((ArgOffset+15)/16)*16; 2413 CurArgOffset = ArgOffset; 2414 ArgOffset += 16; 2415 needsLoad = true; 2416 } 2417 break; 2418 } 2419 2420 // We need to load the argument to a virtual register if we determined 2421 // above that we ran out of physical registers of the appropriate type. 2422 if (needsLoad) { 2423 int FI = MFI->CreateFixedObject(ObjSize, 2424 CurArgOffset + (ArgSize - ObjSize), 2425 isImmutable); 2426 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2427 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(), 2428 false, false, false, 0); 2429 } 2430 2431 InVals.push_back(ArgVal); 2432 } 2433 2434 // Set the size that is at least reserved in caller of this function. Tail 2435 // call optimized functions' reserved stack space needs to be aligned so that 2436 // taking the difference between two stack areas will result in an aligned 2437 // stack. 2438 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true); 2439 2440 // If the function takes variable number of arguments, make a frame index for 2441 // the start of the first vararg value... for expansion of llvm.va_start. 2442 if (isVarArg) { 2443 int Depth = ArgOffset; 2444 2445 FuncInfo->setVarArgsFrameIndex( 2446 MFI->CreateFixedObject(PtrByteSize, Depth, true)); 2447 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2448 2449 // If this function is vararg, store any remaining integer argument regs 2450 // to their spots on the stack so that they may be loaded by deferencing the 2451 // result of va_next. 2452 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 2453 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2454 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2455 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2456 MachinePointerInfo(), false, false, 0); 2457 MemOps.push_back(Store); 2458 // Increment the address by four for the next argument to store 2459 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT); 2460 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 2461 } 2462 } 2463 2464 if (!MemOps.empty()) 2465 Chain = DAG.getNode(ISD::TokenFactor, dl, 2466 MVT::Other, &MemOps[0], MemOps.size()); 2467 2468 return Chain; 2469 } 2470 2471 SDValue 2472 PPCTargetLowering::LowerFormalArguments_Darwin( 2473 SDValue Chain, 2474 CallingConv::ID CallConv, bool isVarArg, 2475 const SmallVectorImpl<ISD::InputArg> 2476 &Ins, 2477 SDLoc dl, SelectionDAG &DAG, 2478 SmallVectorImpl<SDValue> &InVals) const { 2479 // TODO: add description of PPC stack frame format, or at least some docs. 2480 // 2481 MachineFunction &MF = DAG.getMachineFunction(); 2482 MachineFrameInfo *MFI = MF.getFrameInfo(); 2483 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2484 2485 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2486 bool isPPC64 = PtrVT == MVT::i64; 2487 // Potential tail calls could cause overwriting of argument stack slots. 2488 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 2489 (CallConv == CallingConv::Fast)); 2490 unsigned PtrByteSize = isPPC64 ? 8 : 4; 2491 2492 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true); 2493 // Area that is at least reserved in caller of this function. 2494 unsigned MinReservedArea = ArgOffset; 2495 2496 static const uint16_t GPR_32[] = { // 32-bit registers. 2497 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2498 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2499 }; 2500 static const uint16_t GPR_64[] = { // 64-bit registers. 2501 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 2502 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 2503 }; 2504 2505 static const uint16_t *FPR = GetFPR(); 2506 2507 static const uint16_t VR[] = { 2508 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 2509 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 2510 }; 2511 2512 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 2513 const unsigned Num_FPR_Regs = 13; 2514 const unsigned Num_VR_Regs = array_lengthof( VR); 2515 2516 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 2517 2518 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32; 2519 2520 // In 32-bit non-varargs functions, the stack space for vectors is after the 2521 // stack space for non-vectors. We do not use this space unless we have 2522 // too many vectors to fit in registers, something that only occurs in 2523 // constructed examples:), but we have to walk the arglist to figure 2524 // that out...for the pathological case, compute VecArgOffset as the 2525 // start of the vector parameter area. Computing VecArgOffset is the 2526 // entire point of the following loop. 2527 unsigned VecArgOffset = ArgOffset; 2528 if (!isVarArg && !isPPC64) { 2529 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 2530 ++ArgNo) { 2531 EVT ObjectVT = Ins[ArgNo].VT; 2532 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 2533 2534 if (Flags.isByVal()) { 2535 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 2536 unsigned ObjSize = Flags.getByValSize(); 2537 unsigned ArgSize = 2538 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2539 VecArgOffset += ArgSize; 2540 continue; 2541 } 2542 2543 switch(ObjectVT.getSimpleVT().SimpleTy) { 2544 default: llvm_unreachable("Unhandled argument type!"); 2545 case MVT::i32: 2546 case MVT::f32: 2547 VecArgOffset += 4; 2548 break; 2549 case MVT::i64: // PPC64 2550 case MVT::f64: 2551 // FIXME: We are guaranteed to be !isPPC64 at this point. 2552 // Does MVT::i64 apply? 2553 VecArgOffset += 8; 2554 break; 2555 case MVT::v4f32: 2556 case MVT::v4i32: 2557 case MVT::v8i16: 2558 case MVT::v16i8: 2559 // Nothing to do, we're only looking at Nonvector args here. 2560 break; 2561 } 2562 } 2563 } 2564 // We've found where the vector parameter area in memory is. Skip the 2565 // first 12 parameters; these don't use that memory. 2566 VecArgOffset = ((VecArgOffset+15)/16)*16; 2567 VecArgOffset += 12*16; 2568 2569 // Add DAG nodes to load the arguments or copy them out of registers. On 2570 // entry to a function on PPC, the arguments start after the linkage area, 2571 // although the first ones are often in registers. 2572 2573 SmallVector<SDValue, 8> MemOps; 2574 unsigned nAltivecParamsAtEnd = 0; 2575 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 2576 unsigned CurArgIdx = 0; 2577 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 2578 SDValue ArgVal; 2579 bool needsLoad = false; 2580 EVT ObjectVT = Ins[ArgNo].VT; 2581 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 2582 unsigned ArgSize = ObjSize; 2583 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 2584 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx); 2585 CurArgIdx = Ins[ArgNo].OrigArgIndex; 2586 2587 unsigned CurArgOffset = ArgOffset; 2588 2589 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 2590 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 2591 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 2592 if (isVarArg || isPPC64) { 2593 MinReservedArea = ((MinReservedArea+15)/16)*16; 2594 MinReservedArea += CalculateStackSlotSize(ObjectVT, 2595 Flags, 2596 PtrByteSize); 2597 } else nAltivecParamsAtEnd++; 2598 } else 2599 // Calculate min reserved area. 2600 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 2601 Flags, 2602 PtrByteSize); 2603 2604 // FIXME the codegen can be much improved in some cases. 2605 // We do not have to keep everything in memory. 2606 if (Flags.isByVal()) { 2607 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 2608 ObjSize = Flags.getByValSize(); 2609 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2610 // Objects of size 1 and 2 are right justified, everything else is 2611 // left justified. This means the memory address is adjusted forwards. 2612 if (ObjSize==1 || ObjSize==2) { 2613 CurArgOffset = CurArgOffset + (4 - ObjSize); 2614 } 2615 // The value of the object is its address. 2616 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true); 2617 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2618 InVals.push_back(FIN); 2619 if (ObjSize==1 || ObjSize==2) { 2620 if (GPR_idx != Num_GPR_Regs) { 2621 unsigned VReg; 2622 if (isPPC64) 2623 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2624 else 2625 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 2626 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2627 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 2628 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 2629 MachinePointerInfo(FuncArg, 2630 CurArgOffset), 2631 ObjType, false, false, 0); 2632 MemOps.push_back(Store); 2633 ++GPR_idx; 2634 } 2635 2636 ArgOffset += PtrByteSize; 2637 2638 continue; 2639 } 2640 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 2641 // Store whatever pieces of the object are in registers 2642 // to memory. ArgOffset will be the address of the beginning 2643 // of the object. 2644 if (GPR_idx != Num_GPR_Regs) { 2645 unsigned VReg; 2646 if (isPPC64) 2647 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2648 else 2649 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 2650 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); 2651 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2652 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2653 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2654 MachinePointerInfo(FuncArg, ArgOffset), 2655 false, false, 0); 2656 MemOps.push_back(Store); 2657 ++GPR_idx; 2658 ArgOffset += PtrByteSize; 2659 } else { 2660 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 2661 break; 2662 } 2663 } 2664 continue; 2665 } 2666 2667 switch (ObjectVT.getSimpleVT().SimpleTy) { 2668 default: llvm_unreachable("Unhandled argument type!"); 2669 case MVT::i32: 2670 if (!isPPC64) { 2671 if (GPR_idx != Num_GPR_Regs) { 2672 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 2673 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 2674 ++GPR_idx; 2675 } else { 2676 needsLoad = true; 2677 ArgSize = PtrByteSize; 2678 } 2679 // All int arguments reserve stack space in the Darwin ABI. 2680 ArgOffset += PtrByteSize; 2681 break; 2682 } 2683 // FALLTHROUGH 2684 case MVT::i64: // PPC64 2685 if (GPR_idx != Num_GPR_Regs) { 2686 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2687 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 2688 2689 if (ObjectVT == MVT::i32) 2690 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 2691 // value to MVT::i64 and then truncate to the correct register size. 2692 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 2693 2694 ++GPR_idx; 2695 } else { 2696 needsLoad = true; 2697 ArgSize = PtrByteSize; 2698 } 2699 // All int arguments reserve stack space in the Darwin ABI. 2700 ArgOffset += 8; 2701 break; 2702 2703 case MVT::f32: 2704 case MVT::f64: 2705 // Every 4 bytes of argument space consumes one of the GPRs available for 2706 // argument passing. 2707 if (GPR_idx != Num_GPR_Regs) { 2708 ++GPR_idx; 2709 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 2710 ++GPR_idx; 2711 } 2712 if (FPR_idx != Num_FPR_Regs) { 2713 unsigned VReg; 2714 2715 if (ObjectVT == MVT::f32) 2716 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 2717 else 2718 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 2719 2720 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 2721 ++FPR_idx; 2722 } else { 2723 needsLoad = true; 2724 } 2725 2726 // All FP arguments reserve stack space in the Darwin ABI. 2727 ArgOffset += isPPC64 ? 8 : ObjSize; 2728 break; 2729 case MVT::v4f32: 2730 case MVT::v4i32: 2731 case MVT::v8i16: 2732 case MVT::v16i8: 2733 // Note that vector arguments in registers don't reserve stack space, 2734 // except in varargs functions. 2735 if (VR_idx != Num_VR_Regs) { 2736 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 2737 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 2738 if (isVarArg) { 2739 while ((ArgOffset % 16) != 0) { 2740 ArgOffset += PtrByteSize; 2741 if (GPR_idx != Num_GPR_Regs) 2742 GPR_idx++; 2743 } 2744 ArgOffset += 16; 2745 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 2746 } 2747 ++VR_idx; 2748 } else { 2749 if (!isVarArg && !isPPC64) { 2750 // Vectors go after all the nonvectors. 2751 CurArgOffset = VecArgOffset; 2752 VecArgOffset += 16; 2753 } else { 2754 // Vectors are aligned. 2755 ArgOffset = ((ArgOffset+15)/16)*16; 2756 CurArgOffset = ArgOffset; 2757 ArgOffset += 16; 2758 } 2759 needsLoad = true; 2760 } 2761 break; 2762 } 2763 2764 // We need to load the argument to a virtual register if we determined above 2765 // that we ran out of physical registers of the appropriate type. 2766 if (needsLoad) { 2767 int FI = MFI->CreateFixedObject(ObjSize, 2768 CurArgOffset + (ArgSize - ObjSize), 2769 isImmutable); 2770 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2771 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(), 2772 false, false, false, 0); 2773 } 2774 2775 InVals.push_back(ArgVal); 2776 } 2777 2778 // Set the size that is at least reserved in caller of this function. Tail 2779 // call optimized functions' reserved stack space needs to be aligned so that 2780 // taking the difference between two stack areas will result in an aligned 2781 // stack. 2782 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64); 2783 2784 // If the function takes variable number of arguments, make a frame index for 2785 // the start of the first vararg value... for expansion of llvm.va_start. 2786 if (isVarArg) { 2787 int Depth = ArgOffset; 2788 2789 FuncInfo->setVarArgsFrameIndex( 2790 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8, 2791 Depth, true)); 2792 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2793 2794 // If this function is vararg, store any remaining integer argument regs 2795 // to their spots on the stack so that they may be loaded by deferencing the 2796 // result of va_next. 2797 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 2798 unsigned VReg; 2799 2800 if (isPPC64) 2801 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2802 else 2803 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 2804 2805 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2806 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2807 MachinePointerInfo(), false, false, 0); 2808 MemOps.push_back(Store); 2809 // Increment the address by four for the next argument to store 2810 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT); 2811 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 2812 } 2813 } 2814 2815 if (!MemOps.empty()) 2816 Chain = DAG.getNode(ISD::TokenFactor, dl, 2817 MVT::Other, &MemOps[0], MemOps.size()); 2818 2819 return Chain; 2820 } 2821 2822 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus 2823 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI. 2824 static unsigned 2825 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG, 2826 bool isPPC64, 2827 bool isVarArg, 2828 unsigned CC, 2829 const SmallVectorImpl<ISD::OutputArg> 2830 &Outs, 2831 const SmallVectorImpl<SDValue> &OutVals, 2832 unsigned &nAltivecParamsAtEnd) { 2833 // Count how many bytes are to be pushed on the stack, including the linkage 2834 // area, and parameter passing area. We start with 24/48 bytes, which is 2835 // prereserved space for [SP][CR][LR][3 x unused]. 2836 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true); 2837 unsigned NumOps = Outs.size(); 2838 unsigned PtrByteSize = isPPC64 ? 8 : 4; 2839 2840 // Add up all the space actually used. 2841 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 2842 // they all go in registers, but we must reserve stack space for them for 2843 // possible use by the caller. In varargs or 64-bit calls, parameters are 2844 // assigned stack space in order, with padding so Altivec parameters are 2845 // 16-byte aligned. 2846 nAltivecParamsAtEnd = 0; 2847 for (unsigned i = 0; i != NumOps; ++i) { 2848 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2849 EVT ArgVT = Outs[i].VT; 2850 // Varargs Altivec parameters are padded to a 16 byte boundary. 2851 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 || 2852 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) { 2853 if (!isVarArg && !isPPC64) { 2854 // Non-varargs Altivec parameters go after all the non-Altivec 2855 // parameters; handle those later so we know how much padding we need. 2856 nAltivecParamsAtEnd++; 2857 continue; 2858 } 2859 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 2860 NumBytes = ((NumBytes+15)/16)*16; 2861 } 2862 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 2863 } 2864 2865 // Allow for Altivec parameters at the end, if needed. 2866 if (nAltivecParamsAtEnd) { 2867 NumBytes = ((NumBytes+15)/16)*16; 2868 NumBytes += 16*nAltivecParamsAtEnd; 2869 } 2870 2871 // The prolog code of the callee may store up to 8 GPR argument registers to 2872 // the stack, allowing va_start to index over them in memory if its varargs. 2873 // Because we cannot tell if this is needed on the caller side, we have to 2874 // conservatively assume that it is needed. As such, make sure we have at 2875 // least enough stack space for the caller to store the 8 GPRs. 2876 NumBytes = std::max(NumBytes, 2877 PPCFrameLowering::getMinCallFrameSize(isPPC64, true)); 2878 2879 // Tail call needs the stack to be aligned. 2880 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){ 2881 unsigned TargetAlign = DAG.getMachineFunction().getTarget(). 2882 getFrameLowering()->getStackAlignment(); 2883 unsigned AlignMask = TargetAlign-1; 2884 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 2885 } 2886 2887 return NumBytes; 2888 } 2889 2890 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 2891 /// adjusted to accommodate the arguments for the tailcall. 2892 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 2893 unsigned ParamSize) { 2894 2895 if (!isTailCall) return 0; 2896 2897 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 2898 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 2899 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 2900 // Remember only if the new adjustement is bigger. 2901 if (SPDiff < FI->getTailCallSPDelta()) 2902 FI->setTailCallSPDelta(SPDiff); 2903 2904 return SPDiff; 2905 } 2906 2907 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2908 /// for tail call optimization. Targets which want to do tail call 2909 /// optimization should implement this function. 2910 bool 2911 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2912 CallingConv::ID CalleeCC, 2913 bool isVarArg, 2914 const SmallVectorImpl<ISD::InputArg> &Ins, 2915 SelectionDAG& DAG) const { 2916 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 2917 return false; 2918 2919 // Variable argument functions are not supported. 2920 if (isVarArg) 2921 return false; 2922 2923 MachineFunction &MF = DAG.getMachineFunction(); 2924 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 2925 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 2926 // Functions containing by val parameters are not supported. 2927 for (unsigned i = 0; i != Ins.size(); i++) { 2928 ISD::ArgFlagsTy Flags = Ins[i].Flags; 2929 if (Flags.isByVal()) return false; 2930 } 2931 2932 // Non PIC/GOT tail calls are supported. 2933 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 2934 return true; 2935 2936 // At the moment we can only do local tail calls (in same module, hidden 2937 // or protected) if we are generating PIC. 2938 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2939 return G->getGlobal()->hasHiddenVisibility() 2940 || G->getGlobal()->hasProtectedVisibility(); 2941 } 2942 2943 return false; 2944 } 2945 2946 /// isCallCompatibleAddress - Return the immediate to use if the specified 2947 /// 32-bit value is representable in the immediate field of a BxA instruction. 2948 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 2949 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 2950 if (!C) return 0; 2951 2952 int Addr = C->getZExtValue(); 2953 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 2954 SignExtend32<26>(Addr) != Addr) 2955 return 0; // Top 6 bits have to be sext of immediate. 2956 2957 return DAG.getConstant((int)C->getZExtValue() >> 2, 2958 DAG.getTargetLoweringInfo().getPointerTy()).getNode(); 2959 } 2960 2961 namespace { 2962 2963 struct TailCallArgumentInfo { 2964 SDValue Arg; 2965 SDValue FrameIdxOp; 2966 int FrameIdx; 2967 2968 TailCallArgumentInfo() : FrameIdx(0) {} 2969 }; 2970 2971 } 2972 2973 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 2974 static void 2975 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG, 2976 SDValue Chain, 2977 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 2978 SmallVectorImpl<SDValue> &MemOpChains, 2979 SDLoc dl) { 2980 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 2981 SDValue Arg = TailCallArgs[i].Arg; 2982 SDValue FIN = TailCallArgs[i].FrameIdxOp; 2983 int FI = TailCallArgs[i].FrameIdx; 2984 // Store relative to framepointer. 2985 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN, 2986 MachinePointerInfo::getFixedStack(FI), 2987 false, false, 0)); 2988 } 2989 } 2990 2991 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 2992 /// the appropriate stack slot for the tail call optimized function call. 2993 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, 2994 MachineFunction &MF, 2995 SDValue Chain, 2996 SDValue OldRetAddr, 2997 SDValue OldFP, 2998 int SPDiff, 2999 bool isPPC64, 3000 bool isDarwinABI, 3001 SDLoc dl) { 3002 if (SPDiff) { 3003 // Calculate the new stack slot for the return address. 3004 int SlotSize = isPPC64 ? 8 : 4; 3005 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64, 3006 isDarwinABI); 3007 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize, 3008 NewRetAddrLoc, true); 3009 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 3010 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 3011 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 3012 MachinePointerInfo::getFixedStack(NewRetAddr), 3013 false, false, 0); 3014 3015 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 3016 // slot as the FP is never overwritten. 3017 if (isDarwinABI) { 3018 int NewFPLoc = 3019 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI); 3020 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc, 3021 true); 3022 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 3023 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 3024 MachinePointerInfo::getFixedStack(NewFPIdx), 3025 false, false, 0); 3026 } 3027 } 3028 return Chain; 3029 } 3030 3031 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 3032 /// the position of the argument. 3033 static void 3034 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 3035 SDValue Arg, int SPDiff, unsigned ArgOffset, 3036 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 3037 int Offset = ArgOffset + SPDiff; 3038 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8; 3039 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 3040 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 3041 SDValue FIN = DAG.getFrameIndex(FI, VT); 3042 TailCallArgumentInfo Info; 3043 Info.Arg = Arg; 3044 Info.FrameIdxOp = FIN; 3045 Info.FrameIdx = FI; 3046 TailCallArguments.push_back(Info); 3047 } 3048 3049 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 3050 /// stack slot. Returns the chain as result and the loaded frame pointers in 3051 /// LROpOut/FPOpout. Used when tail calling. 3052 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG, 3053 int SPDiff, 3054 SDValue Chain, 3055 SDValue &LROpOut, 3056 SDValue &FPOpOut, 3057 bool isDarwinABI, 3058 SDLoc dl) const { 3059 if (SPDiff) { 3060 // Load the LR and FP stack slot for later adjusting. 3061 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32; 3062 LROpOut = getReturnAddrFrameIndex(DAG); 3063 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(), 3064 false, false, false, 0); 3065 Chain = SDValue(LROpOut.getNode(), 1); 3066 3067 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 3068 // slot as the FP is never overwritten. 3069 if (isDarwinABI) { 3070 FPOpOut = getFramePointerFrameIndex(DAG); 3071 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(), 3072 false, false, false, 0); 3073 Chain = SDValue(FPOpOut.getNode(), 1); 3074 } 3075 } 3076 return Chain; 3077 } 3078 3079 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 3080 /// by "Src" to address "Dst" of size "Size". Alignment information is 3081 /// specified by the specific parameter attribute. The copy will be passed as 3082 /// a byval function parameter. 3083 /// Sometimes what we are copying is the end of a larger object, the part that 3084 /// does not fit in registers. 3085 static SDValue 3086 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 3087 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 3088 SDLoc dl) { 3089 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 3090 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 3091 false, false, MachinePointerInfo(0), 3092 MachinePointerInfo(0)); 3093 } 3094 3095 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 3096 /// tail calls. 3097 static void 3098 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, 3099 SDValue Arg, SDValue PtrOff, int SPDiff, 3100 unsigned ArgOffset, bool isPPC64, bool isTailCall, 3101 bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 3102 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, 3103 SDLoc dl) { 3104 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3105 if (!isTailCall) { 3106 if (isVector) { 3107 SDValue StackPtr; 3108 if (isPPC64) 3109 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 3110 else 3111 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 3112 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 3113 DAG.getConstant(ArgOffset, PtrVT)); 3114 } 3115 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, 3116 MachinePointerInfo(), false, false, 0)); 3117 // Calculate and remember argument location. 3118 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 3119 TailCallArguments); 3120 } 3121 3122 static 3123 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 3124 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes, 3125 SDValue LROp, SDValue FPOp, bool isDarwinABI, 3126 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 3127 MachineFunction &MF = DAG.getMachineFunction(); 3128 3129 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 3130 // might overwrite each other in case of tail call optimization. 3131 SmallVector<SDValue, 8> MemOpChains2; 3132 // Do not flag preceding copytoreg stuff together with the following stuff. 3133 InFlag = SDValue(); 3134 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 3135 MemOpChains2, dl); 3136 if (!MemOpChains2.empty()) 3137 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3138 &MemOpChains2[0], MemOpChains2.size()); 3139 3140 // Store the return address to the appropriate stack slot. 3141 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff, 3142 isPPC64, isDarwinABI, dl); 3143 3144 // Emit callseq_end just before tailcall node. 3145 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 3146 DAG.getIntPtrConstant(0, true), InFlag, dl); 3147 InFlag = Chain.getValue(1); 3148 } 3149 3150 static 3151 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, 3152 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall, 3153 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass, 3154 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 3155 const PPCSubtarget &PPCSubTarget) { 3156 3157 bool isPPC64 = PPCSubTarget.isPPC64(); 3158 bool isSVR4ABI = PPCSubTarget.isSVR4ABI(); 3159 3160 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3161 NodeTys.push_back(MVT::Other); // Returns a chain 3162 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 3163 3164 unsigned CallOpc = PPCISD::CALL; 3165 3166 bool needIndirectCall = true; 3167 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 3168 // If this is an absolute destination address, use the munged value. 3169 Callee = SDValue(Dest, 0); 3170 needIndirectCall = false; 3171 } 3172 3173 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3174 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201 3175 // Use indirect calls for ALL functions calls in JIT mode, since the 3176 // far-call stubs may be outside relocation limits for a BL instruction. 3177 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) { 3178 unsigned OpFlags = 0; 3179 if (DAG.getTarget().getRelocationModel() != Reloc::Static && 3180 (PPCSubTarget.getTargetTriple().isMacOSX() && 3181 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) && 3182 (G->getGlobal()->isDeclaration() || 3183 G->getGlobal()->isWeakForLinker())) { 3184 // PC-relative references to external symbols should go through $stub, 3185 // unless we're building with the leopard linker or later, which 3186 // automatically synthesizes these stubs. 3187 OpFlags = PPCII::MO_DARWIN_STUB; 3188 } 3189 3190 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 3191 // every direct call is) turn it into a TargetGlobalAddress / 3192 // TargetExternalSymbol node so that legalize doesn't hack it. 3193 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 3194 Callee.getValueType(), 3195 0, OpFlags); 3196 needIndirectCall = false; 3197 } 3198 } 3199 3200 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3201 unsigned char OpFlags = 0; 3202 3203 if (DAG.getTarget().getRelocationModel() != Reloc::Static && 3204 (PPCSubTarget.getTargetTriple().isMacOSX() && 3205 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) { 3206 // PC-relative references to external symbols should go through $stub, 3207 // unless we're building with the leopard linker or later, which 3208 // automatically synthesizes these stubs. 3209 OpFlags = PPCII::MO_DARWIN_STUB; 3210 } 3211 3212 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 3213 OpFlags); 3214 needIndirectCall = false; 3215 } 3216 3217 if (needIndirectCall) { 3218 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 3219 // to do the call, we can't use PPCISD::CALL. 3220 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 3221 3222 if (isSVR4ABI && isPPC64) { 3223 // Function pointers in the 64-bit SVR4 ABI do not point to the function 3224 // entry point, but to the function descriptor (the function entry point 3225 // address is part of the function descriptor though). 3226 // The function descriptor is a three doubleword structure with the 3227 // following fields: function entry point, TOC base address and 3228 // environment pointer. 3229 // Thus for a call through a function pointer, the following actions need 3230 // to be performed: 3231 // 1. Save the TOC of the caller in the TOC save area of its stack 3232 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 3233 // 2. Load the address of the function entry point from the function 3234 // descriptor. 3235 // 3. Load the TOC of the callee from the function descriptor into r2. 3236 // 4. Load the environment pointer from the function descriptor into 3237 // r11. 3238 // 5. Branch to the function entry point address. 3239 // 6. On return of the callee, the TOC of the caller needs to be 3240 // restored (this is done in FinishCall()). 3241 // 3242 // All those operations are flagged together to ensure that no other 3243 // operations can be scheduled in between. E.g. without flagging the 3244 // operations together, a TOC access in the caller could be scheduled 3245 // between the load of the callee TOC and the branch to the callee, which 3246 // results in the TOC access going through the TOC of the callee instead 3247 // of going through the TOC of the caller, which leads to incorrect code. 3248 3249 // Load the address of the function entry point from the function 3250 // descriptor. 3251 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue); 3252 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps, 3253 InFlag.getNode() ? 3 : 2); 3254 Chain = LoadFuncPtr.getValue(1); 3255 InFlag = LoadFuncPtr.getValue(2); 3256 3257 // Load environment pointer into r11. 3258 // Offset of the environment pointer within the function descriptor. 3259 SDValue PtrOff = DAG.getIntPtrConstant(16); 3260 3261 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 3262 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr, 3263 InFlag); 3264 Chain = LoadEnvPtr.getValue(1); 3265 InFlag = LoadEnvPtr.getValue(2); 3266 3267 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 3268 InFlag); 3269 Chain = EnvVal.getValue(0); 3270 InFlag = EnvVal.getValue(1); 3271 3272 // Load TOC of the callee into r2. We are using a target-specific load 3273 // with r2 hard coded, because the result of a target-independent load 3274 // would never go directly into r2, since r2 is a reserved register (which 3275 // prevents the register allocator from allocating it), resulting in an 3276 // additional register being allocated and an unnecessary move instruction 3277 // being generated. 3278 VTs = DAG.getVTList(MVT::Other, MVT::Glue); 3279 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, 3280 Callee, InFlag); 3281 Chain = LoadTOCPtr.getValue(0); 3282 InFlag = LoadTOCPtr.getValue(1); 3283 3284 MTCTROps[0] = Chain; 3285 MTCTROps[1] = LoadFuncPtr; 3286 MTCTROps[2] = InFlag; 3287 } 3288 3289 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps, 3290 2 + (InFlag.getNode() != 0)); 3291 InFlag = Chain.getValue(1); 3292 3293 NodeTys.clear(); 3294 NodeTys.push_back(MVT::Other); 3295 NodeTys.push_back(MVT::Glue); 3296 Ops.push_back(Chain); 3297 CallOpc = PPCISD::BCTRL; 3298 Callee.setNode(0); 3299 // Add use of X11 (holding environment pointer) 3300 if (isSVR4ABI && isPPC64) 3301 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 3302 // Add CTR register as callee so a bctr can be emitted later. 3303 if (isTailCall) 3304 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 3305 } 3306 3307 // If this is a direct call, pass the chain and the callee. 3308 if (Callee.getNode()) { 3309 Ops.push_back(Chain); 3310 Ops.push_back(Callee); 3311 } 3312 // If this is a tail call add stack pointer delta. 3313 if (isTailCall) 3314 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32)); 3315 3316 // Add argument registers to the end of the list so that they are known live 3317 // into the call. 3318 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 3319 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 3320 RegsToPass[i].second.getValueType())); 3321 3322 return CallOpc; 3323 } 3324 3325 static 3326 bool isLocalCall(const SDValue &Callee) 3327 { 3328 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 3329 return !G->getGlobal()->isDeclaration() && 3330 !G->getGlobal()->isWeakForLinker(); 3331 return false; 3332 } 3333 3334 SDValue 3335 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 3336 CallingConv::ID CallConv, bool isVarArg, 3337 const SmallVectorImpl<ISD::InputArg> &Ins, 3338 SDLoc dl, SelectionDAG &DAG, 3339 SmallVectorImpl<SDValue> &InVals) const { 3340 3341 SmallVector<CCValAssign, 16> RVLocs; 3342 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3343 getTargetMachine(), RVLocs, *DAG.getContext()); 3344 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); 3345 3346 // Copy all of the result registers out of their specified physreg. 3347 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 3348 CCValAssign &VA = RVLocs[i]; 3349 assert(VA.isRegLoc() && "Can only return in registers!"); 3350 3351 SDValue Val = DAG.getCopyFromReg(Chain, dl, 3352 VA.getLocReg(), VA.getLocVT(), InFlag); 3353 Chain = Val.getValue(1); 3354 InFlag = Val.getValue(2); 3355 3356 switch (VA.getLocInfo()) { 3357 default: llvm_unreachable("Unknown loc info!"); 3358 case CCValAssign::Full: break; 3359 case CCValAssign::AExt: 3360 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 3361 break; 3362 case CCValAssign::ZExt: 3363 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 3364 DAG.getValueType(VA.getValVT())); 3365 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 3366 break; 3367 case CCValAssign::SExt: 3368 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 3369 DAG.getValueType(VA.getValVT())); 3370 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 3371 break; 3372 } 3373 3374 InVals.push_back(Val); 3375 } 3376 3377 return Chain; 3378 } 3379 3380 SDValue 3381 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl, 3382 bool isTailCall, bool isVarArg, 3383 SelectionDAG &DAG, 3384 SmallVector<std::pair<unsigned, SDValue>, 8> 3385 &RegsToPass, 3386 SDValue InFlag, SDValue Chain, 3387 SDValue &Callee, 3388 int SPDiff, unsigned NumBytes, 3389 const SmallVectorImpl<ISD::InputArg> &Ins, 3390 SmallVectorImpl<SDValue> &InVals) const { 3391 std::vector<EVT> NodeTys; 3392 SmallVector<SDValue, 8> Ops; 3393 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff, 3394 isTailCall, RegsToPass, Ops, NodeTys, 3395 PPCSubTarget); 3396 3397 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 3398 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64()) 3399 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 3400 3401 // When performing tail call optimization the callee pops its arguments off 3402 // the stack. Account for this here so these bytes can be pushed back on in 3403 // PPCFrameLowering::eliminateCallFramePseudoInstr. 3404 int BytesCalleePops = 3405 (CallConv == CallingConv::Fast && 3406 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 3407 3408 // Add a register mask operand representing the call-preserved registers. 3409 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo(); 3410 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv); 3411 assert(Mask && "Missing call preserved mask for calling convention"); 3412 Ops.push_back(DAG.getRegisterMask(Mask)); 3413 3414 if (InFlag.getNode()) 3415 Ops.push_back(InFlag); 3416 3417 // Emit tail call. 3418 if (isTailCall) { 3419 assert(((Callee.getOpcode() == ISD::Register && 3420 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 3421 Callee.getOpcode() == ISD::TargetExternalSymbol || 3422 Callee.getOpcode() == ISD::TargetGlobalAddress || 3423 isa<ConstantSDNode>(Callee)) && 3424 "Expecting an global address, external symbol, absolute value or register"); 3425 3426 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size()); 3427 } 3428 3429 // Add a NOP immediately after the branch instruction when using the 64-bit 3430 // SVR4 ABI. At link time, if caller and callee are in a different module and 3431 // thus have a different TOC, the call will be replaced with a call to a stub 3432 // function which saves the current TOC, loads the TOC of the callee and 3433 // branches to the callee. The NOP will be replaced with a load instruction 3434 // which restores the TOC of the caller from the TOC save slot of the current 3435 // stack frame. If caller and callee belong to the same module (and have the 3436 // same TOC), the NOP will remain unchanged. 3437 3438 bool needsTOCRestore = false; 3439 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) { 3440 if (CallOpc == PPCISD::BCTRL) { 3441 // This is a call through a function pointer. 3442 // Restore the caller TOC from the save area into R2. 3443 // See PrepareCall() for more information about calls through function 3444 // pointers in the 64-bit SVR4 ABI. 3445 // We are using a target-specific load with r2 hard coded, because the 3446 // result of a target-independent load would never go directly into r2, 3447 // since r2 is a reserved register (which prevents the register allocator 3448 // from allocating it), resulting in an additional register being 3449 // allocated and an unnecessary move instruction being generated. 3450 needsTOCRestore = true; 3451 } else if ((CallOpc == PPCISD::CALL) && !isLocalCall(Callee)) { 3452 // Otherwise insert NOP for non-local calls. 3453 CallOpc = PPCISD::CALL_NOP; 3454 } 3455 } 3456 3457 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size()); 3458 InFlag = Chain.getValue(1); 3459 3460 if (needsTOCRestore) { 3461 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 3462 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag); 3463 InFlag = Chain.getValue(1); 3464 } 3465 3466 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 3467 DAG.getIntPtrConstant(BytesCalleePops, true), 3468 InFlag, dl); 3469 if (!Ins.empty()) 3470 InFlag = Chain.getValue(1); 3471 3472 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 3473 Ins, dl, DAG, InVals); 3474 } 3475 3476 SDValue 3477 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 3478 SmallVectorImpl<SDValue> &InVals) const { 3479 SelectionDAG &DAG = CLI.DAG; 3480 SDLoc &dl = CLI.DL; 3481 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 3482 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 3483 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 3484 SDValue Chain = CLI.Chain; 3485 SDValue Callee = CLI.Callee; 3486 bool &isTailCall = CLI.IsTailCall; 3487 CallingConv::ID CallConv = CLI.CallConv; 3488 bool isVarArg = CLI.IsVarArg; 3489 3490 if (isTailCall) 3491 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 3492 Ins, DAG); 3493 3494 if (PPCSubTarget.isSVR4ABI()) { 3495 if (PPCSubTarget.isPPC64()) 3496 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 3497 isTailCall, Outs, OutVals, Ins, 3498 dl, DAG, InVals); 3499 else 3500 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 3501 isTailCall, Outs, OutVals, Ins, 3502 dl, DAG, InVals); 3503 } 3504 3505 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 3506 isTailCall, Outs, OutVals, Ins, 3507 dl, DAG, InVals); 3508 } 3509 3510 SDValue 3511 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee, 3512 CallingConv::ID CallConv, bool isVarArg, 3513 bool isTailCall, 3514 const SmallVectorImpl<ISD::OutputArg> &Outs, 3515 const SmallVectorImpl<SDValue> &OutVals, 3516 const SmallVectorImpl<ISD::InputArg> &Ins, 3517 SDLoc dl, SelectionDAG &DAG, 3518 SmallVectorImpl<SDValue> &InVals) const { 3519 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 3520 // of the 32-bit SVR4 ABI stack frame layout. 3521 3522 assert((CallConv == CallingConv::C || 3523 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 3524 3525 unsigned PtrByteSize = 4; 3526 3527 MachineFunction &MF = DAG.getMachineFunction(); 3528 3529 // Mark this function as potentially containing a function that contains a 3530 // tail call. As a consequence the frame pointer will be used for dynamicalloc 3531 // and restoring the callers stack pointer in this functions epilog. This is 3532 // done because by tail calling the called function might overwrite the value 3533 // in this function's (MF) stack pointer stack slot 0(SP). 3534 if (getTargetMachine().Options.GuaranteedTailCallOpt && 3535 CallConv == CallingConv::Fast) 3536 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 3537 3538 // Count how many bytes are to be pushed on the stack, including the linkage 3539 // area, parameter list area and the part of the local variable space which 3540 // contains copies of aggregates which are passed by value. 3541 3542 // Assign locations to all of the outgoing arguments. 3543 SmallVector<CCValAssign, 16> ArgLocs; 3544 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3545 getTargetMachine(), ArgLocs, *DAG.getContext()); 3546 3547 // Reserve space for the linkage area on the stack. 3548 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize); 3549 3550 if (isVarArg) { 3551 // Handle fixed and variable vector arguments differently. 3552 // Fixed vector arguments go into registers as long as registers are 3553 // available. Variable vector arguments always go into memory. 3554 unsigned NumArgs = Outs.size(); 3555 3556 for (unsigned i = 0; i != NumArgs; ++i) { 3557 MVT ArgVT = Outs[i].VT; 3558 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3559 bool Result; 3560 3561 if (Outs[i].IsFixed) { 3562 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 3563 CCInfo); 3564 } else { 3565 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 3566 ArgFlags, CCInfo); 3567 } 3568 3569 if (Result) { 3570 #ifndef NDEBUG 3571 errs() << "Call operand #" << i << " has unhandled type " 3572 << EVT(ArgVT).getEVTString() << "\n"; 3573 #endif 3574 llvm_unreachable(0); 3575 } 3576 } 3577 } else { 3578 // All arguments are treated the same. 3579 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 3580 } 3581 3582 // Assign locations to all of the outgoing aggregate by value arguments. 3583 SmallVector<CCValAssign, 16> ByValArgLocs; 3584 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3585 getTargetMachine(), ByValArgLocs, *DAG.getContext()); 3586 3587 // Reserve stack space for the allocations in CCInfo. 3588 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3589 3590 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 3591 3592 // Size of the linkage area, parameter list area and the part of the local 3593 // space variable where copies of aggregates which are passed by value are 3594 // stored. 3595 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 3596 3597 // Calculate by how many bytes the stack has to be adjusted in case of tail 3598 // call optimization. 3599 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 3600 3601 // Adjust the stack pointer for the new arguments... 3602 // These operations are automatically eliminated by the prolog/epilog pass 3603 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 3604 dl); 3605 SDValue CallSeqStart = Chain; 3606 3607 // Load the return address and frame pointer so it can be moved somewhere else 3608 // later. 3609 SDValue LROp, FPOp; 3610 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false, 3611 dl); 3612 3613 // Set up a copy of the stack pointer for use loading and storing any 3614 // arguments that may not fit in the registers available for argument 3615 // passing. 3616 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 3617 3618 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3619 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 3620 SmallVector<SDValue, 8> MemOpChains; 3621 3622 bool seenFloatArg = false; 3623 // Walk the register/memloc assignments, inserting copies/loads. 3624 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 3625 i != e; 3626 ++i) { 3627 CCValAssign &VA = ArgLocs[i]; 3628 SDValue Arg = OutVals[i]; 3629 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3630 3631 if (Flags.isByVal()) { 3632 // Argument is an aggregate which is passed by value, thus we need to 3633 // create a copy of it in the local variable space of the current stack 3634 // frame (which is the stack frame of the caller) and pass the address of 3635 // this copy to the callee. 3636 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 3637 CCValAssign &ByValVA = ByValArgLocs[j++]; 3638 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 3639 3640 // Memory reserved in the local variable space of the callers stack frame. 3641 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 3642 3643 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 3644 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 3645 3646 // Create a copy of the argument in the local area of the current 3647 // stack frame. 3648 SDValue MemcpyCall = 3649 CreateCopyOfByValArgument(Arg, PtrOff, 3650 CallSeqStart.getNode()->getOperand(0), 3651 Flags, DAG, dl); 3652 3653 // This must go outside the CALLSEQ_START..END. 3654 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 3655 CallSeqStart.getNode()->getOperand(1), 3656 SDLoc(MemcpyCall)); 3657 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 3658 NewCallSeqStart.getNode()); 3659 Chain = CallSeqStart = NewCallSeqStart; 3660 3661 // Pass the address of the aggregate copy on the stack either in a 3662 // physical register or in the parameter list area of the current stack 3663 // frame to the callee. 3664 Arg = PtrOff; 3665 } 3666 3667 if (VA.isRegLoc()) { 3668 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 3669 // Put argument in a physical register. 3670 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3671 } else { 3672 // Put argument in the parameter list area of the current stack frame. 3673 assert(VA.isMemLoc()); 3674 unsigned LocMemOffset = VA.getLocMemOffset(); 3675 3676 if (!isTailCall) { 3677 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 3678 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 3679 3680 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, 3681 MachinePointerInfo(), 3682 false, false, 0)); 3683 } else { 3684 // Calculate and remember argument location. 3685 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 3686 TailCallArguments); 3687 } 3688 } 3689 } 3690 3691 if (!MemOpChains.empty()) 3692 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3693 &MemOpChains[0], MemOpChains.size()); 3694 3695 // Build a sequence of copy-to-reg nodes chained together with token chain 3696 // and flag operands which copy the outgoing args into the appropriate regs. 3697 SDValue InFlag; 3698 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 3699 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 3700 RegsToPass[i].second, InFlag); 3701 InFlag = Chain.getValue(1); 3702 } 3703 3704 // Set CR bit 6 to true if this is a vararg call with floating args passed in 3705 // registers. 3706 if (isVarArg) { 3707 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 3708 SDValue Ops[] = { Chain, InFlag }; 3709 3710 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 3711 dl, VTs, Ops, InFlag.getNode() ? 2 : 1); 3712 3713 InFlag = Chain.getValue(1); 3714 } 3715 3716 if (isTailCall) 3717 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp, 3718 false, TailCallArguments); 3719 3720 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG, 3721 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes, 3722 Ins, InVals); 3723 } 3724 3725 // Copy an argument into memory, being careful to do this outside the 3726 // call sequence for the call to which the argument belongs. 3727 SDValue 3728 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff, 3729 SDValue CallSeqStart, 3730 ISD::ArgFlagsTy Flags, 3731 SelectionDAG &DAG, 3732 SDLoc dl) const { 3733 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 3734 CallSeqStart.getNode()->getOperand(0), 3735 Flags, DAG, dl); 3736 // The MEMCPY must go outside the CALLSEQ_START..END. 3737 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 3738 CallSeqStart.getNode()->getOperand(1), 3739 SDLoc(MemcpyCall)); 3740 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 3741 NewCallSeqStart.getNode()); 3742 return NewCallSeqStart; 3743 } 3744 3745 SDValue 3746 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee, 3747 CallingConv::ID CallConv, bool isVarArg, 3748 bool isTailCall, 3749 const SmallVectorImpl<ISD::OutputArg> &Outs, 3750 const SmallVectorImpl<SDValue> &OutVals, 3751 const SmallVectorImpl<ISD::InputArg> &Ins, 3752 SDLoc dl, SelectionDAG &DAG, 3753 SmallVectorImpl<SDValue> &InVals) const { 3754 3755 unsigned NumOps = Outs.size(); 3756 3757 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3758 unsigned PtrByteSize = 8; 3759 3760 MachineFunction &MF = DAG.getMachineFunction(); 3761 3762 // Mark this function as potentially containing a function that contains a 3763 // tail call. As a consequence the frame pointer will be used for dynamicalloc 3764 // and restoring the callers stack pointer in this functions epilog. This is 3765 // done because by tail calling the called function might overwrite the value 3766 // in this function's (MF) stack pointer stack slot 0(SP). 3767 if (getTargetMachine().Options.GuaranteedTailCallOpt && 3768 CallConv == CallingConv::Fast) 3769 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 3770 3771 unsigned nAltivecParamsAtEnd = 0; 3772 3773 // Count how many bytes are to be pushed on the stack, including the linkage 3774 // area, and parameter passing area. We start with at least 48 bytes, which 3775 // is reserved space for [SP][CR][LR][3 x unused]. 3776 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result 3777 // of this call. 3778 unsigned NumBytes = 3779 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv, 3780 Outs, OutVals, nAltivecParamsAtEnd); 3781 3782 // Calculate by how many bytes the stack has to be adjusted in case of tail 3783 // call optimization. 3784 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 3785 3786 // To protect arguments on the stack from being clobbered in a tail call, 3787 // force all the loads to happen before doing any other lowering. 3788 if (isTailCall) 3789 Chain = DAG.getStackArgumentTokenFactor(Chain); 3790 3791 // Adjust the stack pointer for the new arguments... 3792 // These operations are automatically eliminated by the prolog/epilog pass 3793 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 3794 dl); 3795 SDValue CallSeqStart = Chain; 3796 3797 // Load the return address and frame pointer so it can be move somewhere else 3798 // later. 3799 SDValue LROp, FPOp; 3800 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true, 3801 dl); 3802 3803 // Set up a copy of the stack pointer for use loading and storing any 3804 // arguments that may not fit in the registers available for argument 3805 // passing. 3806 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 3807 3808 // Figure out which arguments are going to go in registers, and which in 3809 // memory. Also, if this is a vararg function, floating point operations 3810 // must be stored to our stack, and loaded into integer regs as well, if 3811 // any integer regs are available for argument passing. 3812 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true); 3813 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3814 3815 static const uint16_t GPR[] = { 3816 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3817 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3818 }; 3819 static const uint16_t *FPR = GetFPR(); 3820 3821 static const uint16_t VR[] = { 3822 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3823 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3824 }; 3825 const unsigned NumGPRs = array_lengthof(GPR); 3826 const unsigned NumFPRs = 13; 3827 const unsigned NumVRs = array_lengthof(VR); 3828 3829 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3830 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 3831 3832 SmallVector<SDValue, 8> MemOpChains; 3833 for (unsigned i = 0; i != NumOps; ++i) { 3834 SDValue Arg = OutVals[i]; 3835 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3836 3837 // PtrOff will be used to store the current argument to the stack if a 3838 // register cannot be found for it. 3839 SDValue PtrOff; 3840 3841 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType()); 3842 3843 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 3844 3845 // Promote integers to 64-bit values. 3846 if (Arg.getValueType() == MVT::i32) { 3847 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 3848 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3849 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 3850 } 3851 3852 // FIXME memcpy is used way more than necessary. Correctness first. 3853 // Note: "by value" is code for passing a structure by value, not 3854 // basic types. 3855 if (Flags.isByVal()) { 3856 // Note: Size includes alignment padding, so 3857 // struct x { short a; char b; } 3858 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 3859 // These are the proper values we need for right-justifying the 3860 // aggregate in a parameter register. 3861 unsigned Size = Flags.getByValSize(); 3862 3863 // An empty aggregate parameter takes up no storage and no 3864 // registers. 3865 if (Size == 0) 3866 continue; 3867 3868 // All aggregates smaller than 8 bytes must be passed right-justified. 3869 if (Size==1 || Size==2 || Size==4) { 3870 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 3871 if (GPR_idx != NumGPRs) { 3872 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 3873 MachinePointerInfo(), VT, 3874 false, false, 0); 3875 MemOpChains.push_back(Load.getValue(1)); 3876 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 3877 3878 ArgOffset += PtrByteSize; 3879 continue; 3880 } 3881 } 3882 3883 if (GPR_idx == NumGPRs && Size < 8) { 3884 SDValue Const = DAG.getConstant(PtrByteSize - Size, 3885 PtrOff.getValueType()); 3886 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 3887 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 3888 CallSeqStart, 3889 Flags, DAG, dl); 3890 ArgOffset += PtrByteSize; 3891 continue; 3892 } 3893 // Copy entire object into memory. There are cases where gcc-generated 3894 // code assumes it is there, even if it could be put entirely into 3895 // registers. (This is not what the doc says.) 3896 3897 // FIXME: The above statement is likely due to a misunderstanding of the 3898 // documents. All arguments must be copied into the parameter area BY 3899 // THE CALLEE in the event that the callee takes the address of any 3900 // formal argument. That has not yet been implemented. However, it is 3901 // reasonable to use the stack area as a staging area for the register 3902 // load. 3903 3904 // Skip this for small aggregates, as we will use the same slot for a 3905 // right-justified copy, below. 3906 if (Size >= 8) 3907 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 3908 CallSeqStart, 3909 Flags, DAG, dl); 3910 3911 // When a register is available, pass a small aggregate right-justified. 3912 if (Size < 8 && GPR_idx != NumGPRs) { 3913 // The easiest way to get this right-justified in a register 3914 // is to copy the structure into the rightmost portion of a 3915 // local variable slot, then load the whole slot into the 3916 // register. 3917 // FIXME: The memcpy seems to produce pretty awful code for 3918 // small aggregates, particularly for packed ones. 3919 // FIXME: It would be preferable to use the slot in the 3920 // parameter save area instead of a new local variable. 3921 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType()); 3922 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 3923 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 3924 CallSeqStart, 3925 Flags, DAG, dl); 3926 3927 // Load the slot into the register. 3928 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff, 3929 MachinePointerInfo(), 3930 false, false, false, 0); 3931 MemOpChains.push_back(Load.getValue(1)); 3932 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 3933 3934 // Done with this argument. 3935 ArgOffset += PtrByteSize; 3936 continue; 3937 } 3938 3939 // For aggregates larger than PtrByteSize, copy the pieces of the 3940 // object that fit into registers from the parameter save area. 3941 for (unsigned j=0; j<Size; j+=PtrByteSize) { 3942 SDValue Const = DAG.getConstant(j, PtrOff.getValueType()); 3943 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 3944 if (GPR_idx != NumGPRs) { 3945 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 3946 MachinePointerInfo(), 3947 false, false, false, 0); 3948 MemOpChains.push_back(Load.getValue(1)); 3949 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 3950 ArgOffset += PtrByteSize; 3951 } else { 3952 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 3953 break; 3954 } 3955 } 3956 continue; 3957 } 3958 3959 switch (Arg.getValueType().getSimpleVT().SimpleTy) { 3960 default: llvm_unreachable("Unexpected ValueType for argument!"); 3961 case MVT::i32: 3962 case MVT::i64: 3963 if (GPR_idx != NumGPRs) { 3964 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 3965 } else { 3966 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 3967 true, isTailCall, false, MemOpChains, 3968 TailCallArguments, dl); 3969 } 3970 ArgOffset += PtrByteSize; 3971 break; 3972 case MVT::f32: 3973 case MVT::f64: 3974 if (FPR_idx != NumFPRs) { 3975 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 3976 3977 if (isVarArg) { 3978 // A single float or an aggregate containing only a single float 3979 // must be passed right-justified in the stack doubleword, and 3980 // in the GPR, if one is available. 3981 SDValue StoreOff; 3982 if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) { 3983 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType()); 3984 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 3985 } else 3986 StoreOff = PtrOff; 3987 3988 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff, 3989 MachinePointerInfo(), false, false, 0); 3990 MemOpChains.push_back(Store); 3991 3992 // Float varargs are always shadowed in available integer registers 3993 if (GPR_idx != NumGPRs) { 3994 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, 3995 MachinePointerInfo(), false, false, 3996 false, 0); 3997 MemOpChains.push_back(Load.getValue(1)); 3998 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 3999 } 4000 } else if (GPR_idx != NumGPRs) 4001 // If we have any FPRs remaining, we may also have GPRs remaining. 4002 ++GPR_idx; 4003 } else { 4004 // Single-precision floating-point values are mapped to the 4005 // second (rightmost) word of the stack doubleword. 4006 if (Arg.getValueType() == MVT::f32) { 4007 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType()); 4008 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 4009 } 4010 4011 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4012 true, isTailCall, false, MemOpChains, 4013 TailCallArguments, dl); 4014 } 4015 ArgOffset += 8; 4016 break; 4017 case MVT::v4f32: 4018 case MVT::v4i32: 4019 case MVT::v8i16: 4020 case MVT::v16i8: 4021 if (isVarArg) { 4022 // These go aligned on the stack, or in the corresponding R registers 4023 // when within range. The Darwin PPC ABI doc claims they also go in 4024 // V registers; in fact gcc does this only for arguments that are 4025 // prototyped, not for those that match the ... We do it for all 4026 // arguments, seems to work. 4027 while (ArgOffset % 16 !=0) { 4028 ArgOffset += PtrByteSize; 4029 if (GPR_idx != NumGPRs) 4030 GPR_idx++; 4031 } 4032 // We could elide this store in the case where the object fits 4033 // entirely in R registers. Maybe later. 4034 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4035 DAG.getConstant(ArgOffset, PtrVT)); 4036 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 4037 MachinePointerInfo(), false, false, 0); 4038 MemOpChains.push_back(Store); 4039 if (VR_idx != NumVRs) { 4040 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, 4041 MachinePointerInfo(), 4042 false, false, false, 0); 4043 MemOpChains.push_back(Load.getValue(1)); 4044 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 4045 } 4046 ArgOffset += 16; 4047 for (unsigned i=0; i<16; i+=PtrByteSize) { 4048 if (GPR_idx == NumGPRs) 4049 break; 4050 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 4051 DAG.getConstant(i, PtrVT)); 4052 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), 4053 false, false, false, 0); 4054 MemOpChains.push_back(Load.getValue(1)); 4055 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4056 } 4057 break; 4058 } 4059 4060 // Non-varargs Altivec params generally go in registers, but have 4061 // stack space allocated at the end. 4062 if (VR_idx != NumVRs) { 4063 // Doesn't have GPR space allocated. 4064 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 4065 } else { 4066 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4067 true, isTailCall, true, MemOpChains, 4068 TailCallArguments, dl); 4069 ArgOffset += 16; 4070 } 4071 break; 4072 } 4073 } 4074 4075 if (!MemOpChains.empty()) 4076 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4077 &MemOpChains[0], MemOpChains.size()); 4078 4079 // Check if this is an indirect call (MTCTR/BCTRL). 4080 // See PrepareCall() for more information about calls through function 4081 // pointers in the 64-bit SVR4 ABI. 4082 if (!isTailCall && 4083 !dyn_cast<GlobalAddressSDNode>(Callee) && 4084 !dyn_cast<ExternalSymbolSDNode>(Callee) && 4085 !isBLACompatibleAddress(Callee, DAG)) { 4086 // Load r2 into a virtual register and store it to the TOC save area. 4087 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 4088 // TOC save area offset. 4089 SDValue PtrOff = DAG.getIntPtrConstant(40); 4090 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 4091 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(), 4092 false, false, 0); 4093 // R12 must contain the address of an indirect callee. This does not 4094 // mean the MTCTR instruction must use R12; it's easier to model this 4095 // as an extra parameter, so do that. 4096 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 4097 } 4098 4099 // Build a sequence of copy-to-reg nodes chained together with token chain 4100 // and flag operands which copy the outgoing args into the appropriate regs. 4101 SDValue InFlag; 4102 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 4103 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 4104 RegsToPass[i].second, InFlag); 4105 InFlag = Chain.getValue(1); 4106 } 4107 4108 if (isTailCall) 4109 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp, 4110 FPOp, true, TailCallArguments); 4111 4112 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG, 4113 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes, 4114 Ins, InVals); 4115 } 4116 4117 SDValue 4118 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee, 4119 CallingConv::ID CallConv, bool isVarArg, 4120 bool isTailCall, 4121 const SmallVectorImpl<ISD::OutputArg> &Outs, 4122 const SmallVectorImpl<SDValue> &OutVals, 4123 const SmallVectorImpl<ISD::InputArg> &Ins, 4124 SDLoc dl, SelectionDAG &DAG, 4125 SmallVectorImpl<SDValue> &InVals) const { 4126 4127 unsigned NumOps = Outs.size(); 4128 4129 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4130 bool isPPC64 = PtrVT == MVT::i64; 4131 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4132 4133 MachineFunction &MF = DAG.getMachineFunction(); 4134 4135 // Mark this function as potentially containing a function that contains a 4136 // tail call. As a consequence the frame pointer will be used for dynamicalloc 4137 // and restoring the callers stack pointer in this functions epilog. This is 4138 // done because by tail calling the called function might overwrite the value 4139 // in this function's (MF) stack pointer stack slot 0(SP). 4140 if (getTargetMachine().Options.GuaranteedTailCallOpt && 4141 CallConv == CallingConv::Fast) 4142 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 4143 4144 unsigned nAltivecParamsAtEnd = 0; 4145 4146 // Count how many bytes are to be pushed on the stack, including the linkage 4147 // area, and parameter passing area. We start with 24/48 bytes, which is 4148 // prereserved space for [SP][CR][LR][3 x unused]. 4149 unsigned NumBytes = 4150 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv, 4151 Outs, OutVals, 4152 nAltivecParamsAtEnd); 4153 4154 // Calculate by how many bytes the stack has to be adjusted in case of tail 4155 // call optimization. 4156 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 4157 4158 // To protect arguments on the stack from being clobbered in a tail call, 4159 // force all the loads to happen before doing any other lowering. 4160 if (isTailCall) 4161 Chain = DAG.getStackArgumentTokenFactor(Chain); 4162 4163 // Adjust the stack pointer for the new arguments... 4164 // These operations are automatically eliminated by the prolog/epilog pass 4165 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 4166 dl); 4167 SDValue CallSeqStart = Chain; 4168 4169 // Load the return address and frame pointer so it can be move somewhere else 4170 // later. 4171 SDValue LROp, FPOp; 4172 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true, 4173 dl); 4174 4175 // Set up a copy of the stack pointer for use loading and storing any 4176 // arguments that may not fit in the registers available for argument 4177 // passing. 4178 SDValue StackPtr; 4179 if (isPPC64) 4180 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4181 else 4182 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4183 4184 // Figure out which arguments are going to go in registers, and which in 4185 // memory. Also, if this is a vararg function, floating point operations 4186 // must be stored to our stack, and loaded into integer regs as well, if 4187 // any integer regs are available for argument passing. 4188 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true); 4189 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4190 4191 static const uint16_t GPR_32[] = { // 32-bit registers. 4192 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4193 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4194 }; 4195 static const uint16_t GPR_64[] = { // 64-bit registers. 4196 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4197 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4198 }; 4199 static const uint16_t *FPR = GetFPR(); 4200 4201 static const uint16_t VR[] = { 4202 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4203 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4204 }; 4205 const unsigned NumGPRs = array_lengthof(GPR_32); 4206 const unsigned NumFPRs = 13; 4207 const unsigned NumVRs = array_lengthof(VR); 4208 4209 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32; 4210 4211 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4212 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 4213 4214 SmallVector<SDValue, 8> MemOpChains; 4215 for (unsigned i = 0; i != NumOps; ++i) { 4216 SDValue Arg = OutVals[i]; 4217 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4218 4219 // PtrOff will be used to store the current argument to the stack if a 4220 // register cannot be found for it. 4221 SDValue PtrOff; 4222 4223 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType()); 4224 4225 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 4226 4227 // On PPC64, promote integers to 64-bit values. 4228 if (isPPC64 && Arg.getValueType() == MVT::i32) { 4229 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 4230 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4231 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 4232 } 4233 4234 // FIXME memcpy is used way more than necessary. Correctness first. 4235 // Note: "by value" is code for passing a structure by value, not 4236 // basic types. 4237 if (Flags.isByVal()) { 4238 unsigned Size = Flags.getByValSize(); 4239 // Very small objects are passed right-justified. Everything else is 4240 // passed left-justified. 4241 if (Size==1 || Size==2) { 4242 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 4243 if (GPR_idx != NumGPRs) { 4244 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 4245 MachinePointerInfo(), VT, 4246 false, false, 0); 4247 MemOpChains.push_back(Load.getValue(1)); 4248 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4249 4250 ArgOffset += PtrByteSize; 4251 } else { 4252 SDValue Const = DAG.getConstant(PtrByteSize - Size, 4253 PtrOff.getValueType()); 4254 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 4255 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 4256 CallSeqStart, 4257 Flags, DAG, dl); 4258 ArgOffset += PtrByteSize; 4259 } 4260 continue; 4261 } 4262 // Copy entire object into memory. There are cases where gcc-generated 4263 // code assumes it is there, even if it could be put entirely into 4264 // registers. (This is not what the doc says.) 4265 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 4266 CallSeqStart, 4267 Flags, DAG, dl); 4268 4269 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 4270 // copy the pieces of the object that fit into registers from the 4271 // parameter save area. 4272 for (unsigned j=0; j<Size; j+=PtrByteSize) { 4273 SDValue Const = DAG.getConstant(j, PtrOff.getValueType()); 4274 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 4275 if (GPR_idx != NumGPRs) { 4276 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 4277 MachinePointerInfo(), 4278 false, false, false, 0); 4279 MemOpChains.push_back(Load.getValue(1)); 4280 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4281 ArgOffset += PtrByteSize; 4282 } else { 4283 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 4284 break; 4285 } 4286 } 4287 continue; 4288 } 4289 4290 switch (Arg.getValueType().getSimpleVT().SimpleTy) { 4291 default: llvm_unreachable("Unexpected ValueType for argument!"); 4292 case MVT::i32: 4293 case MVT::i64: 4294 if (GPR_idx != NumGPRs) { 4295 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 4296 } else { 4297 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4298 isPPC64, isTailCall, false, MemOpChains, 4299 TailCallArguments, dl); 4300 } 4301 ArgOffset += PtrByteSize; 4302 break; 4303 case MVT::f32: 4304 case MVT::f64: 4305 if (FPR_idx != NumFPRs) { 4306 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 4307 4308 if (isVarArg) { 4309 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 4310 MachinePointerInfo(), false, false, 0); 4311 MemOpChains.push_back(Store); 4312 4313 // Float varargs are always shadowed in available integer registers 4314 if (GPR_idx != NumGPRs) { 4315 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, 4316 MachinePointerInfo(), false, false, 4317 false, 0); 4318 MemOpChains.push_back(Load.getValue(1)); 4319 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4320 } 4321 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 4322 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType()); 4323 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 4324 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, 4325 MachinePointerInfo(), 4326 false, false, false, 0); 4327 MemOpChains.push_back(Load.getValue(1)); 4328 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4329 } 4330 } else { 4331 // If we have any FPRs remaining, we may also have GPRs remaining. 4332 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 4333 // GPRs. 4334 if (GPR_idx != NumGPRs) 4335 ++GPR_idx; 4336 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 4337 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 4338 ++GPR_idx; 4339 } 4340 } else 4341 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4342 isPPC64, isTailCall, false, MemOpChains, 4343 TailCallArguments, dl); 4344 if (isPPC64) 4345 ArgOffset += 8; 4346 else 4347 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 4348 break; 4349 case MVT::v4f32: 4350 case MVT::v4i32: 4351 case MVT::v8i16: 4352 case MVT::v16i8: 4353 if (isVarArg) { 4354 // These go aligned on the stack, or in the corresponding R registers 4355 // when within range. The Darwin PPC ABI doc claims they also go in 4356 // V registers; in fact gcc does this only for arguments that are 4357 // prototyped, not for those that match the ... We do it for all 4358 // arguments, seems to work. 4359 while (ArgOffset % 16 !=0) { 4360 ArgOffset += PtrByteSize; 4361 if (GPR_idx != NumGPRs) 4362 GPR_idx++; 4363 } 4364 // We could elide this store in the case where the object fits 4365 // entirely in R registers. Maybe later. 4366 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4367 DAG.getConstant(ArgOffset, PtrVT)); 4368 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 4369 MachinePointerInfo(), false, false, 0); 4370 MemOpChains.push_back(Store); 4371 if (VR_idx != NumVRs) { 4372 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, 4373 MachinePointerInfo(), 4374 false, false, false, 0); 4375 MemOpChains.push_back(Load.getValue(1)); 4376 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 4377 } 4378 ArgOffset += 16; 4379 for (unsigned i=0; i<16; i+=PtrByteSize) { 4380 if (GPR_idx == NumGPRs) 4381 break; 4382 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 4383 DAG.getConstant(i, PtrVT)); 4384 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), 4385 false, false, false, 0); 4386 MemOpChains.push_back(Load.getValue(1)); 4387 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4388 } 4389 break; 4390 } 4391 4392 // Non-varargs Altivec params generally go in registers, but have 4393 // stack space allocated at the end. 4394 if (VR_idx != NumVRs) { 4395 // Doesn't have GPR space allocated. 4396 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 4397 } else if (nAltivecParamsAtEnd==0) { 4398 // We are emitting Altivec params in order. 4399 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4400 isPPC64, isTailCall, true, MemOpChains, 4401 TailCallArguments, dl); 4402 ArgOffset += 16; 4403 } 4404 break; 4405 } 4406 } 4407 // If all Altivec parameters fit in registers, as they usually do, 4408 // they get stack space following the non-Altivec parameters. We 4409 // don't track this here because nobody below needs it. 4410 // If there are more Altivec parameters than fit in registers emit 4411 // the stores here. 4412 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 4413 unsigned j = 0; 4414 // Offset is aligned; skip 1st 12 params which go in V registers. 4415 ArgOffset = ((ArgOffset+15)/16)*16; 4416 ArgOffset += 12*16; 4417 for (unsigned i = 0; i != NumOps; ++i) { 4418 SDValue Arg = OutVals[i]; 4419 EVT ArgType = Outs[i].VT; 4420 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 4421 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 4422 if (++j > NumVRs) { 4423 SDValue PtrOff; 4424 // We are emitting Altivec params in order. 4425 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4426 isPPC64, isTailCall, true, MemOpChains, 4427 TailCallArguments, dl); 4428 ArgOffset += 16; 4429 } 4430 } 4431 } 4432 } 4433 4434 if (!MemOpChains.empty()) 4435 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4436 &MemOpChains[0], MemOpChains.size()); 4437 4438 // On Darwin, R12 must contain the address of an indirect callee. This does 4439 // not mean the MTCTR instruction must use R12; it's easier to model this as 4440 // an extra parameter, so do that. 4441 if (!isTailCall && 4442 !dyn_cast<GlobalAddressSDNode>(Callee) && 4443 !dyn_cast<ExternalSymbolSDNode>(Callee) && 4444 !isBLACompatibleAddress(Callee, DAG)) 4445 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 4446 PPC::R12), Callee)); 4447 4448 // Build a sequence of copy-to-reg nodes chained together with token chain 4449 // and flag operands which copy the outgoing args into the appropriate regs. 4450 SDValue InFlag; 4451 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 4452 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 4453 RegsToPass[i].second, InFlag); 4454 InFlag = Chain.getValue(1); 4455 } 4456 4457 if (isTailCall) 4458 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp, 4459 FPOp, true, TailCallArguments); 4460 4461 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG, 4462 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes, 4463 Ins, InVals); 4464 } 4465 4466 bool 4467 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 4468 MachineFunction &MF, bool isVarArg, 4469 const SmallVectorImpl<ISD::OutputArg> &Outs, 4470 LLVMContext &Context) const { 4471 SmallVector<CCValAssign, 16> RVLocs; 4472 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 4473 RVLocs, Context); 4474 return CCInfo.CheckReturn(Outs, RetCC_PPC); 4475 } 4476 4477 SDValue 4478 PPCTargetLowering::LowerReturn(SDValue Chain, 4479 CallingConv::ID CallConv, bool isVarArg, 4480 const SmallVectorImpl<ISD::OutputArg> &Outs, 4481 const SmallVectorImpl<SDValue> &OutVals, 4482 SDLoc dl, SelectionDAG &DAG) const { 4483 4484 SmallVector<CCValAssign, 16> RVLocs; 4485 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 4486 getTargetMachine(), RVLocs, *DAG.getContext()); 4487 CCInfo.AnalyzeReturn(Outs, RetCC_PPC); 4488 4489 SDValue Flag; 4490 SmallVector<SDValue, 4> RetOps(1, Chain); 4491 4492 // Copy the result values into the output registers. 4493 for (unsigned i = 0; i != RVLocs.size(); ++i) { 4494 CCValAssign &VA = RVLocs[i]; 4495 assert(VA.isRegLoc() && "Can only return in registers!"); 4496 4497 SDValue Arg = OutVals[i]; 4498 4499 switch (VA.getLocInfo()) { 4500 default: llvm_unreachable("Unknown loc info!"); 4501 case CCValAssign::Full: break; 4502 case CCValAssign::AExt: 4503 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 4504 break; 4505 case CCValAssign::ZExt: 4506 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 4507 break; 4508 case CCValAssign::SExt: 4509 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 4510 break; 4511 } 4512 4513 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 4514 Flag = Chain.getValue(1); 4515 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 4516 } 4517 4518 RetOps[0] = Chain; // Update chain. 4519 4520 // Add the flag if we have it. 4521 if (Flag.getNode()) 4522 RetOps.push_back(Flag); 4523 4524 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, 4525 &RetOps[0], RetOps.size()); 4526 } 4527 4528 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG, 4529 const PPCSubtarget &Subtarget) const { 4530 // When we pop the dynamic allocation we need to restore the SP link. 4531 SDLoc dl(Op); 4532 4533 // Get the corect type for pointers. 4534 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4535 4536 // Construct the stack pointer operand. 4537 bool isPPC64 = Subtarget.isPPC64(); 4538 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 4539 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 4540 4541 // Get the operands for the STACKRESTORE. 4542 SDValue Chain = Op.getOperand(0); 4543 SDValue SaveSP = Op.getOperand(1); 4544 4545 // Load the old link SP. 4546 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr, 4547 MachinePointerInfo(), 4548 false, false, false, 0); 4549 4550 // Restore the stack pointer. 4551 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 4552 4553 // Store the old link SP. 4554 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(), 4555 false, false, 0); 4556 } 4557 4558 4559 4560 SDValue 4561 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const { 4562 MachineFunction &MF = DAG.getMachineFunction(); 4563 bool isPPC64 = PPCSubTarget.isPPC64(); 4564 bool isDarwinABI = PPCSubTarget.isDarwinABI(); 4565 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4566 4567 // Get current frame pointer save index. The users of this index will be 4568 // primarily DYNALLOC instructions. 4569 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 4570 int RASI = FI->getReturnAddrSaveIndex(); 4571 4572 // If the frame pointer save index hasn't been defined yet. 4573 if (!RASI) { 4574 // Find out what the fix offset of the frame pointer save area. 4575 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI); 4576 // Allocate the frame index for frame pointer save area. 4577 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true); 4578 // Save the result. 4579 FI->setReturnAddrSaveIndex(RASI); 4580 } 4581 return DAG.getFrameIndex(RASI, PtrVT); 4582 } 4583 4584 SDValue 4585 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 4586 MachineFunction &MF = DAG.getMachineFunction(); 4587 bool isPPC64 = PPCSubTarget.isPPC64(); 4588 bool isDarwinABI = PPCSubTarget.isDarwinABI(); 4589 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4590 4591 // Get current frame pointer save index. The users of this index will be 4592 // primarily DYNALLOC instructions. 4593 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 4594 int FPSI = FI->getFramePointerSaveIndex(); 4595 4596 // If the frame pointer save index hasn't been defined yet. 4597 if (!FPSI) { 4598 // Find out what the fix offset of the frame pointer save area. 4599 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64, 4600 isDarwinABI); 4601 4602 // Allocate the frame index for frame pointer save area. 4603 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 4604 // Save the result. 4605 FI->setFramePointerSaveIndex(FPSI); 4606 } 4607 return DAG.getFrameIndex(FPSI, PtrVT); 4608 } 4609 4610 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 4611 SelectionDAG &DAG, 4612 const PPCSubtarget &Subtarget) const { 4613 // Get the inputs. 4614 SDValue Chain = Op.getOperand(0); 4615 SDValue Size = Op.getOperand(1); 4616 SDLoc dl(Op); 4617 4618 // Get the corect type for pointers. 4619 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4620 // Negate the size. 4621 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 4622 DAG.getConstant(0, PtrVT), Size); 4623 // Construct a node for the frame pointer save index. 4624 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 4625 // Build a DYNALLOC node. 4626 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 4627 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 4628 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3); 4629 } 4630 4631 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 4632 SelectionDAG &DAG) const { 4633 SDLoc DL(Op); 4634 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 4635 DAG.getVTList(MVT::i32, MVT::Other), 4636 Op.getOperand(0), Op.getOperand(1)); 4637 } 4638 4639 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 4640 SelectionDAG &DAG) const { 4641 SDLoc DL(Op); 4642 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 4643 Op.getOperand(0), Op.getOperand(1)); 4644 } 4645 4646 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 4647 /// possible. 4648 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4649 // Not FP? Not a fsel. 4650 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 4651 !Op.getOperand(2).getValueType().isFloatingPoint()) 4652 return Op; 4653 4654 // We might be able to do better than this under some circumstances, but in 4655 // general, fsel-based lowering of select is a finite-math-only optimization. 4656 // For more information, see section F.3 of the 2.06 ISA specification. 4657 if (!DAG.getTarget().Options.NoInfsFPMath || 4658 !DAG.getTarget().Options.NoNaNsFPMath) 4659 return Op; 4660 4661 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4662 4663 EVT ResVT = Op.getValueType(); 4664 EVT CmpVT = Op.getOperand(0).getValueType(); 4665 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 4666 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 4667 SDLoc dl(Op); 4668 4669 // If the RHS of the comparison is a 0.0, we don't need to do the 4670 // subtraction at all. 4671 SDValue Sel1; 4672 if (isFloatingPointZero(RHS)) 4673 switch (CC) { 4674 default: break; // SETUO etc aren't handled by fsel. 4675 case ISD::SETNE: 4676 std::swap(TV, FV); 4677 case ISD::SETEQ: 4678 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 4679 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 4680 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 4681 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 4682 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 4683 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 4684 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 4685 case ISD::SETULT: 4686 case ISD::SETLT: 4687 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 4688 case ISD::SETOGE: 4689 case ISD::SETGE: 4690 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 4691 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 4692 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 4693 case ISD::SETUGT: 4694 case ISD::SETGT: 4695 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 4696 case ISD::SETOLE: 4697 case ISD::SETLE: 4698 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 4699 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 4700 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 4701 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 4702 } 4703 4704 SDValue Cmp; 4705 switch (CC) { 4706 default: break; // SETUO etc aren't handled by fsel. 4707 case ISD::SETNE: 4708 std::swap(TV, FV); 4709 case ISD::SETEQ: 4710 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 4711 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 4712 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 4713 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 4714 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 4715 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 4716 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 4717 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 4718 case ISD::SETULT: 4719 case ISD::SETLT: 4720 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 4721 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 4722 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 4723 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 4724 case ISD::SETOGE: 4725 case ISD::SETGE: 4726 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 4727 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 4728 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 4729 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 4730 case ISD::SETUGT: 4731 case ISD::SETGT: 4732 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS); 4733 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 4734 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 4735 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 4736 case ISD::SETOLE: 4737 case ISD::SETLE: 4738 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS); 4739 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 4740 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 4741 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 4742 } 4743 return Op; 4744 } 4745 4746 // FIXME: Split this code up when LegalizeDAGTypes lands. 4747 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 4748 SDLoc dl) const { 4749 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 4750 SDValue Src = Op.getOperand(0); 4751 if (Src.getValueType() == MVT::f32) 4752 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 4753 4754 SDValue Tmp; 4755 switch (Op.getValueType().getSimpleVT().SimpleTy) { 4756 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 4757 case MVT::i32: 4758 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ : 4759 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ : 4760 PPCISD::FCTIDZ), 4761 dl, MVT::f64, Src); 4762 break; 4763 case MVT::i64: 4764 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) && 4765 "i64 FP_TO_UINT is supported only with FPCVT"); 4766 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 4767 PPCISD::FCTIDUZ, 4768 dl, MVT::f64, Src); 4769 break; 4770 } 4771 4772 // Convert the FP value to an int value through memory. 4773 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() && 4774 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()); 4775 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 4776 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 4777 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI); 4778 4779 // Emit a store to the stack slot. 4780 SDValue Chain; 4781 if (i32Stack) { 4782 MachineFunction &MF = DAG.getMachineFunction(); 4783 MachineMemOperand *MMO = 4784 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 4785 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 4786 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 4787 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops), 4788 MVT::i32, MMO); 4789 } else 4790 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, 4791 MPI, false, false, 0); 4792 4793 // Result is a load from the stack slot. If loading 4 bytes, make sure to 4794 // add in a bias. 4795 if (Op.getValueType() == MVT::i32 && !i32Stack) { 4796 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 4797 DAG.getConstant(4, FIPtr.getValueType())); 4798 MPI = MachinePointerInfo(); 4799 } 4800 4801 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI, 4802 false, false, false, 0); 4803 } 4804 4805 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 4806 SelectionDAG &DAG) const { 4807 SDLoc dl(Op); 4808 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 4809 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 4810 return SDValue(); 4811 4812 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) && 4813 "UINT_TO_FP is supported only with FPCVT"); 4814 4815 // If we have FCFIDS, then use it when converting to single-precision. 4816 // Otherwise, convert to double-precision and then round. 4817 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ? 4818 (Op.getOpcode() == ISD::UINT_TO_FP ? 4819 PPCISD::FCFIDUS : PPCISD::FCFIDS) : 4820 (Op.getOpcode() == ISD::UINT_TO_FP ? 4821 PPCISD::FCFIDU : PPCISD::FCFID); 4822 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ? 4823 MVT::f32 : MVT::f64; 4824 4825 if (Op.getOperand(0).getValueType() == MVT::i64) { 4826 SDValue SINT = Op.getOperand(0); 4827 // When converting to single-precision, we actually need to convert 4828 // to double-precision first and then round to single-precision. 4829 // To avoid double-rounding effects during that operation, we have 4830 // to prepare the input operand. Bits that might be truncated when 4831 // converting to double-precision are replaced by a bit that won't 4832 // be lost at this stage, but is below the single-precision rounding 4833 // position. 4834 // 4835 // However, if -enable-unsafe-fp-math is in effect, accept double 4836 // rounding to avoid the extra overhead. 4837 if (Op.getValueType() == MVT::f32 && 4838 !PPCSubTarget.hasFPCVT() && 4839 !DAG.getTarget().Options.UnsafeFPMath) { 4840 4841 // Twiddle input to make sure the low 11 bits are zero. (If this 4842 // is the case, we are guaranteed the value will fit into the 53 bit 4843 // mantissa of an IEEE double-precision value without rounding.) 4844 // If any of those low 11 bits were not zero originally, make sure 4845 // bit 12 (value 2048) is set instead, so that the final rounding 4846 // to single-precision gets the correct result. 4847 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 4848 SINT, DAG.getConstant(2047, MVT::i64)); 4849 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 4850 Round, DAG.getConstant(2047, MVT::i64)); 4851 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 4852 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 4853 Round, DAG.getConstant(-2048, MVT::i64)); 4854 4855 // However, we cannot use that value unconditionally: if the magnitude 4856 // of the input value is small, the bit-twiddling we did above might 4857 // end up visibly changing the output. Fortunately, in that case, we 4858 // don't need to twiddle bits since the original input will convert 4859 // exactly to double-precision floating-point already. Therefore, 4860 // construct a conditional to use the original value if the top 11 4861 // bits are all sign-bit copies, and use the rounded value computed 4862 // above otherwise. 4863 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 4864 SINT, DAG.getConstant(53, MVT::i32)); 4865 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 4866 Cond, DAG.getConstant(1, MVT::i64)); 4867 Cond = DAG.getSetCC(dl, MVT::i32, 4868 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT); 4869 4870 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 4871 } 4872 4873 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 4874 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 4875 4876 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT()) 4877 FP = DAG.getNode(ISD::FP_ROUND, dl, 4878 MVT::f32, FP, DAG.getIntPtrConstant(0)); 4879 return FP; 4880 } 4881 4882 assert(Op.getOperand(0).getValueType() == MVT::i32 && 4883 "Unhandled INT_TO_FP type in custom expander!"); 4884 // Since we only generate this in 64-bit mode, we can take advantage of 4885 // 64-bit registers. In particular, sign extend the input value into the 4886 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 4887 // then lfd it and fcfid it. 4888 MachineFunction &MF = DAG.getMachineFunction(); 4889 MachineFrameInfo *FrameInfo = MF.getFrameInfo(); 4890 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4891 4892 SDValue Ld; 4893 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) { 4894 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false); 4895 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 4896 4897 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 4898 MachinePointerInfo::getFixedStack(FrameIdx), 4899 false, false, 0); 4900 4901 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 4902 "Expected an i32 store"); 4903 MachineMemOperand *MMO = 4904 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx), 4905 MachineMemOperand::MOLoad, 4, 4); 4906 SDValue Ops[] = { Store, FIdx }; 4907 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 4908 PPCISD::LFIWZX : PPCISD::LFIWAX, 4909 dl, DAG.getVTList(MVT::f64, MVT::Other), 4910 Ops, 2, MVT::i32, MMO); 4911 } else { 4912 assert(PPCSubTarget.isPPC64() && 4913 "i32->FP without LFIWAX supported only on PPC64"); 4914 4915 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false); 4916 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 4917 4918 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 4919 Op.getOperand(0)); 4920 4921 // STD the extended value into the stack slot. 4922 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx, 4923 MachinePointerInfo::getFixedStack(FrameIdx), 4924 false, false, 0); 4925 4926 // Load the value as a double. 4927 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, 4928 MachinePointerInfo::getFixedStack(FrameIdx), 4929 false, false, false, 0); 4930 } 4931 4932 // FCFID it and return it. 4933 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 4934 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT()) 4935 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0)); 4936 return FP; 4937 } 4938 4939 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4940 SelectionDAG &DAG) const { 4941 SDLoc dl(Op); 4942 /* 4943 The rounding mode is in bits 30:31 of FPSR, and has the following 4944 settings: 4945 00 Round to nearest 4946 01 Round to 0 4947 10 Round to +inf 4948 11 Round to -inf 4949 4950 FLT_ROUNDS, on the other hand, expects the following: 4951 -1 Undefined 4952 0 Round to 0 4953 1 Round to nearest 4954 2 Round to +inf 4955 3 Round to -inf 4956 4957 To perform the conversion, we do: 4958 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 4959 */ 4960 4961 MachineFunction &MF = DAG.getMachineFunction(); 4962 EVT VT = Op.getValueType(); 4963 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4964 SDValue MFFSreg, InFlag; 4965 4966 // Save FP Control Word to register 4967 EVT NodeTys[] = { 4968 MVT::f64, // return register 4969 MVT::Glue // unused in this context 4970 }; 4971 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0); 4972 4973 // Save FP register to stack slot 4974 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false); 4975 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 4976 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, 4977 StackSlot, MachinePointerInfo(), false, false,0); 4978 4979 // Load FP Control Word from low 32 bits of stack slot. 4980 SDValue Four = DAG.getConstant(4, PtrVT); 4981 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 4982 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(), 4983 false, false, false, 0); 4984 4985 // Transform as necessary 4986 SDValue CWD1 = 4987 DAG.getNode(ISD::AND, dl, MVT::i32, 4988 CWD, DAG.getConstant(3, MVT::i32)); 4989 SDValue CWD2 = 4990 DAG.getNode(ISD::SRL, dl, MVT::i32, 4991 DAG.getNode(ISD::AND, dl, MVT::i32, 4992 DAG.getNode(ISD::XOR, dl, MVT::i32, 4993 CWD, DAG.getConstant(3, MVT::i32)), 4994 DAG.getConstant(3, MVT::i32)), 4995 DAG.getConstant(1, MVT::i32)); 4996 4997 SDValue RetVal = 4998 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 4999 5000 return DAG.getNode((VT.getSizeInBits() < 16 ? 5001 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 5002 } 5003 5004 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 5005 EVT VT = Op.getValueType(); 5006 unsigned BitWidth = VT.getSizeInBits(); 5007 SDLoc dl(Op); 5008 assert(Op.getNumOperands() == 3 && 5009 VT == Op.getOperand(1).getValueType() && 5010 "Unexpected SHL!"); 5011 5012 // Expand into a bunch of logical ops. Note that these ops 5013 // depend on the PPC behavior for oversized shift amounts. 5014 SDValue Lo = Op.getOperand(0); 5015 SDValue Hi = Op.getOperand(1); 5016 SDValue Amt = Op.getOperand(2); 5017 EVT AmtVT = Amt.getValueType(); 5018 5019 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 5020 DAG.getConstant(BitWidth, AmtVT), Amt); 5021 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 5022 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 5023 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 5024 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 5025 DAG.getConstant(-BitWidth, AmtVT)); 5026 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 5027 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 5028 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 5029 SDValue OutOps[] = { OutLo, OutHi }; 5030 return DAG.getMergeValues(OutOps, 2, dl); 5031 } 5032 5033 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 5034 EVT VT = Op.getValueType(); 5035 SDLoc dl(Op); 5036 unsigned BitWidth = VT.getSizeInBits(); 5037 assert(Op.getNumOperands() == 3 && 5038 VT == Op.getOperand(1).getValueType() && 5039 "Unexpected SRL!"); 5040 5041 // Expand into a bunch of logical ops. Note that these ops 5042 // depend on the PPC behavior for oversized shift amounts. 5043 SDValue Lo = Op.getOperand(0); 5044 SDValue Hi = Op.getOperand(1); 5045 SDValue Amt = Op.getOperand(2); 5046 EVT AmtVT = Amt.getValueType(); 5047 5048 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 5049 DAG.getConstant(BitWidth, AmtVT), Amt); 5050 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 5051 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 5052 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 5053 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 5054 DAG.getConstant(-BitWidth, AmtVT)); 5055 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 5056 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 5057 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 5058 SDValue OutOps[] = { OutLo, OutHi }; 5059 return DAG.getMergeValues(OutOps, 2, dl); 5060 } 5061 5062 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 5063 SDLoc dl(Op); 5064 EVT VT = Op.getValueType(); 5065 unsigned BitWidth = VT.getSizeInBits(); 5066 assert(Op.getNumOperands() == 3 && 5067 VT == Op.getOperand(1).getValueType() && 5068 "Unexpected SRA!"); 5069 5070 // Expand into a bunch of logical ops, followed by a select_cc. 5071 SDValue Lo = Op.getOperand(0); 5072 SDValue Hi = Op.getOperand(1); 5073 SDValue Amt = Op.getOperand(2); 5074 EVT AmtVT = Amt.getValueType(); 5075 5076 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 5077 DAG.getConstant(BitWidth, AmtVT), Amt); 5078 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 5079 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 5080 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 5081 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 5082 DAG.getConstant(-BitWidth, AmtVT)); 5083 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 5084 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 5085 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT), 5086 Tmp4, Tmp6, ISD::SETLE); 5087 SDValue OutOps[] = { OutLo, OutHi }; 5088 return DAG.getMergeValues(OutOps, 2, dl); 5089 } 5090 5091 //===----------------------------------------------------------------------===// 5092 // Vector related lowering. 5093 // 5094 5095 /// BuildSplatI - Build a canonical splati of Val with an element size of 5096 /// SplatSize. Cast the result to VT. 5097 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 5098 SelectionDAG &DAG, SDLoc dl) { 5099 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 5100 5101 static const EVT VTys[] = { // canonical VT to use for each size. 5102 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 5103 }; 5104 5105 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 5106 5107 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 5108 if (Val == -1) 5109 SplatSize = 1; 5110 5111 EVT CanonicalVT = VTys[SplatSize-1]; 5112 5113 // Build a canonical splat for this value. 5114 SDValue Elt = DAG.getConstant(Val, MVT::i32); 5115 SmallVector<SDValue, 8> Ops; 5116 Ops.assign(CanonicalVT.getVectorNumElements(), Elt); 5117 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, 5118 &Ops[0], Ops.size()); 5119 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res); 5120 } 5121 5122 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 5123 /// specified intrinsic ID. 5124 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, 5125 SelectionDAG &DAG, SDLoc dl, 5126 EVT DestVT = MVT::Other) { 5127 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 5128 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 5129 DAG.getConstant(IID, MVT::i32), Op); 5130 } 5131 5132 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 5133 /// specified intrinsic ID. 5134 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 5135 SelectionDAG &DAG, SDLoc dl, 5136 EVT DestVT = MVT::Other) { 5137 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 5138 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 5139 DAG.getConstant(IID, MVT::i32), LHS, RHS); 5140 } 5141 5142 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 5143 /// specified intrinsic ID. 5144 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 5145 SDValue Op2, SelectionDAG &DAG, 5146 SDLoc dl, EVT DestVT = MVT::Other) { 5147 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 5148 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 5149 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2); 5150 } 5151 5152 5153 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 5154 /// amount. The result has the specified value type. 5155 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, 5156 EVT VT, SelectionDAG &DAG, SDLoc dl) { 5157 // Force LHS/RHS to be the right type. 5158 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 5159 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 5160 5161 int Ops[16]; 5162 for (unsigned i = 0; i != 16; ++i) 5163 Ops[i] = i + Amt; 5164 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 5165 return DAG.getNode(ISD::BITCAST, dl, VT, T); 5166 } 5167 5168 // If this is a case we can't handle, return null and let the default 5169 // expansion code take care of it. If we CAN select this case, and if it 5170 // selects to a single instruction, return Op. Otherwise, if we can codegen 5171 // this case more efficiently than a constant pool load, lower it to the 5172 // sequence of ops that should be used. 5173 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 5174 SelectionDAG &DAG) const { 5175 SDLoc dl(Op); 5176 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 5177 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 5178 5179 // Check if this is a splat of a constant value. 5180 APInt APSplatBits, APSplatUndef; 5181 unsigned SplatBitSize; 5182 bool HasAnyUndefs; 5183 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 5184 HasAnyUndefs, 0, true) || SplatBitSize > 32) 5185 return SDValue(); 5186 5187 unsigned SplatBits = APSplatBits.getZExtValue(); 5188 unsigned SplatUndef = APSplatUndef.getZExtValue(); 5189 unsigned SplatSize = SplatBitSize / 8; 5190 5191 // First, handle single instruction cases. 5192 5193 // All zeros? 5194 if (SplatBits == 0) { 5195 // Canonicalize all zero vectors to be v4i32. 5196 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 5197 SDValue Z = DAG.getConstant(0, MVT::i32); 5198 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z); 5199 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 5200 } 5201 return Op; 5202 } 5203 5204 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 5205 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 5206 (32-SplatBitSize)); 5207 if (SextVal >= -16 && SextVal <= 15) 5208 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 5209 5210 5211 // Two instruction sequences. 5212 5213 // If this value is in the range [-32,30] and is even, use: 5214 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 5215 // If this value is in the range [17,31] and is odd, use: 5216 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 5217 // If this value is in the range [-31,-17] and is odd, use: 5218 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 5219 // Note the last two are three-instruction sequences. 5220 if (SextVal >= -32 && SextVal <= 31) { 5221 // To avoid having these optimizations undone by constant folding, 5222 // we convert to a pseudo that will be expanded later into one of 5223 // the above forms. 5224 SDValue Elt = DAG.getConstant(SextVal, MVT::i32); 5225 EVT VT = Op.getValueType(); 5226 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4); 5227 SDValue EltSize = DAG.getConstant(Size, MVT::i32); 5228 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 5229 } 5230 5231 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 5232 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 5233 // for fneg/fabs. 5234 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 5235 // Make -1 and vspltisw -1: 5236 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 5237 5238 // Make the VSLW intrinsic, computing 0x8000_0000. 5239 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 5240 OnesV, DAG, dl); 5241 5242 // xor by OnesV to invert it. 5243 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 5244 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 5245 } 5246 5247 // Check to see if this is a wide variety of vsplti*, binop self cases. 5248 static const signed char SplatCsts[] = { 5249 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 5250 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 5251 }; 5252 5253 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 5254 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 5255 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 5256 int i = SplatCsts[idx]; 5257 5258 // Figure out what shift amount will be used by altivec if shifted by i in 5259 // this splat size. 5260 unsigned TypeShiftAmt = i & (SplatBitSize-1); 5261 5262 // vsplti + shl self. 5263 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 5264 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 5265 static const unsigned IIDs[] = { // Intrinsic to use for each size. 5266 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 5267 Intrinsic::ppc_altivec_vslw 5268 }; 5269 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 5270 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 5271 } 5272 5273 // vsplti + srl self. 5274 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 5275 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 5276 static const unsigned IIDs[] = { // Intrinsic to use for each size. 5277 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 5278 Intrinsic::ppc_altivec_vsrw 5279 }; 5280 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 5281 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 5282 } 5283 5284 // vsplti + sra self. 5285 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 5286 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 5287 static const unsigned IIDs[] = { // Intrinsic to use for each size. 5288 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 5289 Intrinsic::ppc_altivec_vsraw 5290 }; 5291 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 5292 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 5293 } 5294 5295 // vsplti + rol self. 5296 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 5297 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 5298 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 5299 static const unsigned IIDs[] = { // Intrinsic to use for each size. 5300 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 5301 Intrinsic::ppc_altivec_vrlw 5302 }; 5303 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 5304 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 5305 } 5306 5307 // t = vsplti c, result = vsldoi t, t, 1 5308 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 5309 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 5310 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl); 5311 } 5312 // t = vsplti c, result = vsldoi t, t, 2 5313 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 5314 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 5315 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl); 5316 } 5317 // t = vsplti c, result = vsldoi t, t, 3 5318 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 5319 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 5320 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl); 5321 } 5322 } 5323 5324 return SDValue(); 5325 } 5326 5327 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5328 /// the specified operations to build the shuffle. 5329 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5330 SDValue RHS, SelectionDAG &DAG, 5331 SDLoc dl) { 5332 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5333 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5334 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5335 5336 enum { 5337 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5338 OP_VMRGHW, 5339 OP_VMRGLW, 5340 OP_VSPLTISW0, 5341 OP_VSPLTISW1, 5342 OP_VSPLTISW2, 5343 OP_VSPLTISW3, 5344 OP_VSLDOI4, 5345 OP_VSLDOI8, 5346 OP_VSLDOI12 5347 }; 5348 5349 if (OpNum == OP_COPY) { 5350 if (LHSID == (1*9+2)*9+3) return LHS; 5351 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 5352 return RHS; 5353 } 5354 5355 SDValue OpLHS, OpRHS; 5356 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5357 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5358 5359 int ShufIdxs[16]; 5360 switch (OpNum) { 5361 default: llvm_unreachable("Unknown i32 permute!"); 5362 case OP_VMRGHW: 5363 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 5364 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 5365 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 5366 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 5367 break; 5368 case OP_VMRGLW: 5369 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 5370 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 5371 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 5372 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 5373 break; 5374 case OP_VSPLTISW0: 5375 for (unsigned i = 0; i != 16; ++i) 5376 ShufIdxs[i] = (i&3)+0; 5377 break; 5378 case OP_VSPLTISW1: 5379 for (unsigned i = 0; i != 16; ++i) 5380 ShufIdxs[i] = (i&3)+4; 5381 break; 5382 case OP_VSPLTISW2: 5383 for (unsigned i = 0; i != 16; ++i) 5384 ShufIdxs[i] = (i&3)+8; 5385 break; 5386 case OP_VSPLTISW3: 5387 for (unsigned i = 0; i != 16; ++i) 5388 ShufIdxs[i] = (i&3)+12; 5389 break; 5390 case OP_VSLDOI4: 5391 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 5392 case OP_VSLDOI8: 5393 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 5394 case OP_VSLDOI12: 5395 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 5396 } 5397 EVT VT = OpLHS.getValueType(); 5398 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 5399 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 5400 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 5401 return DAG.getNode(ISD::BITCAST, dl, VT, T); 5402 } 5403 5404 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 5405 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 5406 /// return the code it can be lowered into. Worst case, it can always be 5407 /// lowered into a vperm. 5408 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 5409 SelectionDAG &DAG) const { 5410 SDLoc dl(Op); 5411 SDValue V1 = Op.getOperand(0); 5412 SDValue V2 = Op.getOperand(1); 5413 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5414 EVT VT = Op.getValueType(); 5415 5416 // Cases that are handled by instructions that take permute immediates 5417 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 5418 // selected by the instruction selector. 5419 if (V2.getOpcode() == ISD::UNDEF) { 5420 if (PPC::isSplatShuffleMask(SVOp, 1) || 5421 PPC::isSplatShuffleMask(SVOp, 2) || 5422 PPC::isSplatShuffleMask(SVOp, 4) || 5423 PPC::isVPKUWUMShuffleMask(SVOp, true) || 5424 PPC::isVPKUHUMShuffleMask(SVOp, true) || 5425 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 || 5426 PPC::isVMRGLShuffleMask(SVOp, 1, true) || 5427 PPC::isVMRGLShuffleMask(SVOp, 2, true) || 5428 PPC::isVMRGLShuffleMask(SVOp, 4, true) || 5429 PPC::isVMRGHShuffleMask(SVOp, 1, true) || 5430 PPC::isVMRGHShuffleMask(SVOp, 2, true) || 5431 PPC::isVMRGHShuffleMask(SVOp, 4, true)) { 5432 return Op; 5433 } 5434 } 5435 5436 // Altivec has a variety of "shuffle immediates" that take two vector inputs 5437 // and produce a fixed permutation. If any of these match, do not lower to 5438 // VPERM. 5439 if (PPC::isVPKUWUMShuffleMask(SVOp, false) || 5440 PPC::isVPKUHUMShuffleMask(SVOp, false) || 5441 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 || 5442 PPC::isVMRGLShuffleMask(SVOp, 1, false) || 5443 PPC::isVMRGLShuffleMask(SVOp, 2, false) || 5444 PPC::isVMRGLShuffleMask(SVOp, 4, false) || 5445 PPC::isVMRGHShuffleMask(SVOp, 1, false) || 5446 PPC::isVMRGHShuffleMask(SVOp, 2, false) || 5447 PPC::isVMRGHShuffleMask(SVOp, 4, false)) 5448 return Op; 5449 5450 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 5451 // perfect shuffle table to emit an optimal matching sequence. 5452 ArrayRef<int> PermMask = SVOp->getMask(); 5453 5454 unsigned PFIndexes[4]; 5455 bool isFourElementShuffle = true; 5456 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 5457 unsigned EltNo = 8; // Start out undef. 5458 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 5459 if (PermMask[i*4+j] < 0) 5460 continue; // Undef, ignore it. 5461 5462 unsigned ByteSource = PermMask[i*4+j]; 5463 if ((ByteSource & 3) != j) { 5464 isFourElementShuffle = false; 5465 break; 5466 } 5467 5468 if (EltNo == 8) { 5469 EltNo = ByteSource/4; 5470 } else if (EltNo != ByteSource/4) { 5471 isFourElementShuffle = false; 5472 break; 5473 } 5474 } 5475 PFIndexes[i] = EltNo; 5476 } 5477 5478 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 5479 // perfect shuffle vector to determine if it is cost effective to do this as 5480 // discrete instructions, or whether we should use a vperm. 5481 if (isFourElementShuffle) { 5482 // Compute the index in the perfect shuffle table. 5483 unsigned PFTableIndex = 5484 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5485 5486 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5487 unsigned Cost = (PFEntry >> 30); 5488 5489 // Determining when to avoid vperm is tricky. Many things affect the cost 5490 // of vperm, particularly how many times the perm mask needs to be computed. 5491 // For example, if the perm mask can be hoisted out of a loop or is already 5492 // used (perhaps because there are multiple permutes with the same shuffle 5493 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 5494 // the loop requires an extra register. 5495 // 5496 // As a compromise, we only emit discrete instructions if the shuffle can be 5497 // generated in 3 or fewer operations. When we have loop information 5498 // available, if this block is within a loop, we should avoid using vperm 5499 // for 3-operation perms and use a constant pool load instead. 5500 if (Cost < 3) 5501 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 5502 } 5503 5504 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 5505 // vector that will get spilled to the constant pool. 5506 if (V2.getOpcode() == ISD::UNDEF) V2 = V1; 5507 5508 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 5509 // that it is in input element units, not in bytes. Convert now. 5510 EVT EltVT = V1.getValueType().getVectorElementType(); 5511 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 5512 5513 SmallVector<SDValue, 16> ResultMask; 5514 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5515 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 5516 5517 for (unsigned j = 0; j != BytesPerElement; ++j) 5518 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j, 5519 MVT::i32)); 5520 } 5521 5522 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8, 5523 &ResultMask[0], ResultMask.size()); 5524 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask); 5525 } 5526 5527 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an 5528 /// altivec comparison. If it is, return true and fill in Opc/isDot with 5529 /// information about the intrinsic. 5530 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc, 5531 bool &isDot) { 5532 unsigned IntrinsicID = 5533 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 5534 CompareOpc = -1; 5535 isDot = false; 5536 switch (IntrinsicID) { 5537 default: return false; 5538 // Comparison predicates. 5539 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break; 5540 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break; 5541 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break; 5542 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break; 5543 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break; 5544 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break; 5545 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break; 5546 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break; 5547 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break; 5548 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break; 5549 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break; 5550 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break; 5551 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break; 5552 5553 // Normal Comparisons. 5554 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break; 5555 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break; 5556 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break; 5557 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break; 5558 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break; 5559 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break; 5560 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break; 5561 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break; 5562 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break; 5563 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break; 5564 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break; 5565 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break; 5566 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break; 5567 } 5568 return true; 5569 } 5570 5571 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 5572 /// lower, do it, otherwise return null. 5573 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5574 SelectionDAG &DAG) const { 5575 // If this is a lowered altivec predicate compare, CompareOpc is set to the 5576 // opcode number of the comparison. 5577 SDLoc dl(Op); 5578 int CompareOpc; 5579 bool isDot; 5580 if (!getAltivecCompareInfo(Op, CompareOpc, isDot)) 5581 return SDValue(); // Don't custom lower most intrinsics. 5582 5583 // If this is a non-dot comparison, make the VCMP node and we are done. 5584 if (!isDot) { 5585 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 5586 Op.getOperand(1), Op.getOperand(2), 5587 DAG.getConstant(CompareOpc, MVT::i32)); 5588 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 5589 } 5590 5591 // Create the PPCISD altivec 'dot' comparison node. 5592 SDValue Ops[] = { 5593 Op.getOperand(2), // LHS 5594 Op.getOperand(3), // RHS 5595 DAG.getConstant(CompareOpc, MVT::i32) 5596 }; 5597 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 5598 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3); 5599 5600 // Now that we have the comparison, emit a copy from the CR to a GPR. 5601 // This is flagged to the above dot comparison. 5602 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 5603 DAG.getRegister(PPC::CR6, MVT::i32), 5604 CompNode.getValue(1)); 5605 5606 // Unpack the result based on how the target uses it. 5607 unsigned BitNo; // Bit # of CR6. 5608 bool InvertBit; // Invert result? 5609 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 5610 default: // Can't happen, don't crash on invalid number though. 5611 case 0: // Return the value of the EQ bit of CR6. 5612 BitNo = 0; InvertBit = false; 5613 break; 5614 case 1: // Return the inverted value of the EQ bit of CR6. 5615 BitNo = 0; InvertBit = true; 5616 break; 5617 case 2: // Return the value of the LT bit of CR6. 5618 BitNo = 2; InvertBit = false; 5619 break; 5620 case 3: // Return the inverted value of the LT bit of CR6. 5621 BitNo = 2; InvertBit = true; 5622 break; 5623 } 5624 5625 // Shift the bit into the low position. 5626 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 5627 DAG.getConstant(8-(3-BitNo), MVT::i32)); 5628 // Isolate the bit. 5629 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 5630 DAG.getConstant(1, MVT::i32)); 5631 5632 // If we are supposed to, toggle the bit. 5633 if (InvertBit) 5634 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 5635 DAG.getConstant(1, MVT::i32)); 5636 return Flags; 5637 } 5638 5639 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 5640 SelectionDAG &DAG) const { 5641 SDLoc dl(Op); 5642 // Create a stack slot that is 16-byte aligned. 5643 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 5644 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); 5645 EVT PtrVT = getPointerTy(); 5646 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 5647 5648 // Store the input value into Value#0 of the stack slot. 5649 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, 5650 Op.getOperand(0), FIdx, MachinePointerInfo(), 5651 false, false, 0); 5652 // Load it out. 5653 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(), 5654 false, false, false, 0); 5655 } 5656 5657 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 5658 SDLoc dl(Op); 5659 if (Op.getValueType() == MVT::v4i32) { 5660 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 5661 5662 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 5663 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 5664 5665 SDValue RHSSwap = // = vrlw RHS, 16 5666 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 5667 5668 // Shrinkify inputs to v8i16. 5669 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 5670 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 5671 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 5672 5673 // Low parts multiplied together, generating 32-bit results (we ignore the 5674 // top parts). 5675 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 5676 LHS, RHS, DAG, dl, MVT::v4i32); 5677 5678 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 5679 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 5680 // Shift the high parts up 16 bits. 5681 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 5682 Neg16, DAG, dl); 5683 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 5684 } else if (Op.getValueType() == MVT::v8i16) { 5685 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 5686 5687 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 5688 5689 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 5690 LHS, RHS, Zero, DAG, dl); 5691 } else if (Op.getValueType() == MVT::v16i8) { 5692 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 5693 5694 // Multiply the even 8-bit parts, producing 16-bit sums. 5695 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 5696 LHS, RHS, DAG, dl, MVT::v8i16); 5697 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 5698 5699 // Multiply the odd 8-bit parts, producing 16-bit sums. 5700 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 5701 LHS, RHS, DAG, dl, MVT::v8i16); 5702 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 5703 5704 // Merge the results together. 5705 int Ops[16]; 5706 for (unsigned i = 0; i != 8; ++i) { 5707 Ops[i*2 ] = 2*i+1; 5708 Ops[i*2+1] = 2*i+1+16; 5709 } 5710 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 5711 } else { 5712 llvm_unreachable("Unknown mul to lower!"); 5713 } 5714 } 5715 5716 /// LowerOperation - Provide custom lowering hooks for some operations. 5717 /// 5718 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 5719 switch (Op.getOpcode()) { 5720 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 5721 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 5722 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 5723 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 5724 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 5725 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 5726 case ISD::SETCC: return LowerSETCC(Op, DAG); 5727 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 5728 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 5729 case ISD::VASTART: 5730 return LowerVASTART(Op, DAG, PPCSubTarget); 5731 5732 case ISD::VAARG: 5733 return LowerVAARG(Op, DAG, PPCSubTarget); 5734 5735 case ISD::VACOPY: 5736 return LowerVACOPY(Op, DAG, PPCSubTarget); 5737 5738 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget); 5739 case ISD::DYNAMIC_STACKALLOC: 5740 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget); 5741 5742 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 5743 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 5744 5745 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 5746 case ISD::FP_TO_UINT: 5747 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 5748 SDLoc(Op)); 5749 case ISD::UINT_TO_FP: 5750 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 5751 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 5752 5753 // Lower 64-bit shifts. 5754 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 5755 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 5756 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 5757 5758 // Vector-related lowering. 5759 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 5760 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 5761 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 5762 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 5763 case ISD::MUL: return LowerMUL(Op, DAG); 5764 5765 // For counter-based loop handling. 5766 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 5767 5768 // Frame & Return address. 5769 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 5770 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 5771 } 5772 } 5773 5774 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 5775 SmallVectorImpl<SDValue>&Results, 5776 SelectionDAG &DAG) const { 5777 const TargetMachine &TM = getTargetMachine(); 5778 SDLoc dl(N); 5779 switch (N->getOpcode()) { 5780 default: 5781 llvm_unreachable("Do not know how to custom type legalize this operation!"); 5782 case ISD::INTRINSIC_W_CHAIN: { 5783 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 5784 Intrinsic::ppc_is_decremented_ctr_nonzero) 5785 break; 5786 5787 assert(N->getValueType(0) == MVT::i1 && 5788 "Unexpected result type for CTR decrement intrinsic"); 5789 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0)); 5790 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 5791 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 5792 N->getOperand(1)); 5793 5794 Results.push_back(NewInt); 5795 Results.push_back(NewInt.getValue(1)); 5796 break; 5797 } 5798 case ISD::VAARG: { 5799 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI() 5800 || TM.getSubtarget<PPCSubtarget>().isPPC64()) 5801 return; 5802 5803 EVT VT = N->getValueType(0); 5804 5805 if (VT == MVT::i64) { 5806 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget); 5807 5808 Results.push_back(NewNode); 5809 Results.push_back(NewNode.getValue(1)); 5810 } 5811 return; 5812 } 5813 case ISD::FP_ROUND_INREG: { 5814 assert(N->getValueType(0) == MVT::ppcf128); 5815 assert(N->getOperand(0).getValueType() == MVT::ppcf128); 5816 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 5817 MVT::f64, N->getOperand(0), 5818 DAG.getIntPtrConstant(0)); 5819 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 5820 MVT::f64, N->getOperand(0), 5821 DAG.getIntPtrConstant(1)); 5822 5823 // Add the two halves of the long double in round-to-zero mode. 5824 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 5825 5826 // We know the low half is about to be thrown away, so just use something 5827 // convenient. 5828 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 5829 FPreg, FPreg)); 5830 return; 5831 } 5832 case ISD::FP_TO_SINT: 5833 // LowerFP_TO_INT() can only handle f32 and f64. 5834 if (N->getOperand(0).getValueType() == MVT::ppcf128) 5835 return; 5836 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 5837 return; 5838 } 5839 } 5840 5841 5842 //===----------------------------------------------------------------------===// 5843 // Other Lowering Code 5844 //===----------------------------------------------------------------------===// 5845 5846 MachineBasicBlock * 5847 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB, 5848 bool is64bit, unsigned BinOpcode) const { 5849 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 5850 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 5851 5852 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 5853 MachineFunction *F = BB->getParent(); 5854 MachineFunction::iterator It = BB; 5855 ++It; 5856 5857 unsigned dest = MI->getOperand(0).getReg(); 5858 unsigned ptrA = MI->getOperand(1).getReg(); 5859 unsigned ptrB = MI->getOperand(2).getReg(); 5860 unsigned incr = MI->getOperand(3).getReg(); 5861 DebugLoc dl = MI->getDebugLoc(); 5862 5863 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 5864 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 5865 F->insert(It, loopMBB); 5866 F->insert(It, exitMBB); 5867 exitMBB->splice(exitMBB->begin(), BB, 5868 llvm::next(MachineBasicBlock::iterator(MI)), 5869 BB->end()); 5870 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 5871 5872 MachineRegisterInfo &RegInfo = F->getRegInfo(); 5873 unsigned TmpReg = (!BinOpcode) ? incr : 5874 RegInfo.createVirtualRegister( 5875 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass : 5876 (const TargetRegisterClass *) &PPC::GPRCRegClass); 5877 5878 // thisMBB: 5879 // ... 5880 // fallthrough --> loopMBB 5881 BB->addSuccessor(loopMBB); 5882 5883 // loopMBB: 5884 // l[wd]arx dest, ptr 5885 // add r0, dest, incr 5886 // st[wd]cx. r0, ptr 5887 // bne- loopMBB 5888 // fallthrough --> exitMBB 5889 BB = loopMBB; 5890 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest) 5891 .addReg(ptrA).addReg(ptrB); 5892 if (BinOpcode) 5893 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 5894 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 5895 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 5896 BuildMI(BB, dl, TII->get(PPC::BCC)) 5897 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 5898 BB->addSuccessor(loopMBB); 5899 BB->addSuccessor(exitMBB); 5900 5901 // exitMBB: 5902 // ... 5903 BB = exitMBB; 5904 return BB; 5905 } 5906 5907 MachineBasicBlock * 5908 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI, 5909 MachineBasicBlock *BB, 5910 bool is8bit, // operation 5911 unsigned BinOpcode) const { 5912 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 5913 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 5914 // In 64 bit mode we have to use 64 bits for addresses, even though the 5915 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 5916 // registers without caring whether they're 32 or 64, but here we're 5917 // doing actual arithmetic on the addresses. 5918 bool is64bit = PPCSubTarget.isPPC64(); 5919 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 5920 5921 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 5922 MachineFunction *F = BB->getParent(); 5923 MachineFunction::iterator It = BB; 5924 ++It; 5925 5926 unsigned dest = MI->getOperand(0).getReg(); 5927 unsigned ptrA = MI->getOperand(1).getReg(); 5928 unsigned ptrB = MI->getOperand(2).getReg(); 5929 unsigned incr = MI->getOperand(3).getReg(); 5930 DebugLoc dl = MI->getDebugLoc(); 5931 5932 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 5933 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 5934 F->insert(It, loopMBB); 5935 F->insert(It, exitMBB); 5936 exitMBB->splice(exitMBB->begin(), BB, 5937 llvm::next(MachineBasicBlock::iterator(MI)), 5938 BB->end()); 5939 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 5940 5941 MachineRegisterInfo &RegInfo = F->getRegInfo(); 5942 const TargetRegisterClass *RC = 5943 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass : 5944 (const TargetRegisterClass *) &PPC::GPRCRegClass; 5945 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 5946 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 5947 unsigned ShiftReg = RegInfo.createVirtualRegister(RC); 5948 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 5949 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 5950 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 5951 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 5952 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 5953 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 5954 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 5955 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 5956 unsigned Ptr1Reg; 5957 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 5958 5959 // thisMBB: 5960 // ... 5961 // fallthrough --> loopMBB 5962 BB->addSuccessor(loopMBB); 5963 5964 // The 4-byte load must be aligned, while a char or short may be 5965 // anywhere in the word. Hence all this nasty bookkeeping code. 5966 // add ptr1, ptrA, ptrB [copy if ptrA==0] 5967 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 5968 // xori shift, shift1, 24 [16] 5969 // rlwinm ptr, ptr1, 0, 0, 29 5970 // slw incr2, incr, shift 5971 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 5972 // slw mask, mask2, shift 5973 // loopMBB: 5974 // lwarx tmpDest, ptr 5975 // add tmp, tmpDest, incr2 5976 // andc tmp2, tmpDest, mask 5977 // and tmp3, tmp, mask 5978 // or tmp4, tmp3, tmp2 5979 // stwcx. tmp4, ptr 5980 // bne- loopMBB 5981 // fallthrough --> exitMBB 5982 // srw dest, tmpDest, shift 5983 if (ptrA != ZeroReg) { 5984 Ptr1Reg = RegInfo.createVirtualRegister(RC); 5985 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 5986 .addReg(ptrA).addReg(ptrB); 5987 } else { 5988 Ptr1Reg = ptrB; 5989 } 5990 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 5991 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 5992 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 5993 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 5994 if (is64bit) 5995 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 5996 .addReg(Ptr1Reg).addImm(0).addImm(61); 5997 else 5998 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 5999 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 6000 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 6001 .addReg(incr).addReg(ShiftReg); 6002 if (is8bit) 6003 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 6004 else { 6005 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 6006 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 6007 } 6008 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 6009 .addReg(Mask2Reg).addReg(ShiftReg); 6010 6011 BB = loopMBB; 6012 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 6013 .addReg(ZeroReg).addReg(PtrReg); 6014 if (BinOpcode) 6015 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 6016 .addReg(Incr2Reg).addReg(TmpDestReg); 6017 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 6018 .addReg(TmpDestReg).addReg(MaskReg); 6019 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 6020 .addReg(TmpReg).addReg(MaskReg); 6021 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 6022 .addReg(Tmp3Reg).addReg(Tmp2Reg); 6023 BuildMI(BB, dl, TII->get(PPC::STWCX)) 6024 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 6025 BuildMI(BB, dl, TII->get(PPC::BCC)) 6026 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 6027 BB->addSuccessor(loopMBB); 6028 BB->addSuccessor(exitMBB); 6029 6030 // exitMBB: 6031 // ... 6032 BB = exitMBB; 6033 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 6034 .addReg(ShiftReg); 6035 return BB; 6036 } 6037 6038 llvm::MachineBasicBlock* 6039 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI, 6040 MachineBasicBlock *MBB) const { 6041 DebugLoc DL = MI->getDebugLoc(); 6042 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6043 6044 MachineFunction *MF = MBB->getParent(); 6045 MachineRegisterInfo &MRI = MF->getRegInfo(); 6046 6047 const BasicBlock *BB = MBB->getBasicBlock(); 6048 MachineFunction::iterator I = MBB; 6049 ++I; 6050 6051 // Memory Reference 6052 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 6053 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 6054 6055 unsigned DstReg = MI->getOperand(0).getReg(); 6056 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 6057 assert(RC->hasType(MVT::i32) && "Invalid destination!"); 6058 unsigned mainDstReg = MRI.createVirtualRegister(RC); 6059 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 6060 6061 MVT PVT = getPointerTy(); 6062 assert((PVT == MVT::i64 || PVT == MVT::i32) && 6063 "Invalid Pointer Size!"); 6064 // For v = setjmp(buf), we generate 6065 // 6066 // thisMBB: 6067 // SjLjSetup mainMBB 6068 // bl mainMBB 6069 // v_restore = 1 6070 // b sinkMBB 6071 // 6072 // mainMBB: 6073 // buf[LabelOffset] = LR 6074 // v_main = 0 6075 // 6076 // sinkMBB: 6077 // v = phi(main, restore) 6078 // 6079 6080 MachineBasicBlock *thisMBB = MBB; 6081 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 6082 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 6083 MF->insert(I, mainMBB); 6084 MF->insert(I, sinkMBB); 6085 6086 MachineInstrBuilder MIB; 6087 6088 // Transfer the remainder of BB and its successor edges to sinkMBB. 6089 sinkMBB->splice(sinkMBB->begin(), MBB, 6090 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 6091 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 6092 6093 // Note that the structure of the jmp_buf used here is not compatible 6094 // with that used by libc, and is not designed to be. Specifically, it 6095 // stores only those 'reserved' registers that LLVM does not otherwise 6096 // understand how to spill. Also, by convention, by the time this 6097 // intrinsic is called, Clang has already stored the frame address in the 6098 // first slot of the buffer and stack address in the third. Following the 6099 // X86 target code, we'll store the jump address in the second slot. We also 6100 // need to save the TOC pointer (R2) to handle jumps between shared 6101 // libraries, and that will be stored in the fourth slot. The thread 6102 // identifier (R13) is not affected. 6103 6104 // thisMBB: 6105 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 6106 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 6107 const int64_t BPOffset = 4 * PVT.getStoreSize(); 6108 6109 // Prepare IP either in reg. 6110 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 6111 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 6112 unsigned BufReg = MI->getOperand(1).getReg(); 6113 6114 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) { 6115 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 6116 .addReg(PPC::X2) 6117 .addImm(TOCOffset) 6118 .addReg(BufReg); 6119 MIB.setMemRefs(MMOBegin, MMOEnd); 6120 } 6121 6122 // Naked functions never have a base pointer, and so we use r1. For all 6123 // other functions, this decision must be delayed until during PEI. 6124 unsigned BaseReg; 6125 if (MF->getFunction()->getAttributes().hasAttribute( 6126 AttributeSet::FunctionIndex, Attribute::Naked)) 6127 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1; 6128 else 6129 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP; 6130 6131 MIB = BuildMI(*thisMBB, MI, DL, 6132 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW)) 6133 .addReg(BaseReg) 6134 .addImm(BPOffset) 6135 .addReg(BufReg); 6136 MIB.setMemRefs(MMOBegin, MMOEnd); 6137 6138 // Setup 6139 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 6140 const PPCRegisterInfo *TRI = 6141 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo()); 6142 MIB.addRegMask(TRI->getNoPreservedMask()); 6143 6144 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 6145 6146 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 6147 .addMBB(mainMBB); 6148 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 6149 6150 thisMBB->addSuccessor(mainMBB, /* weight */ 0); 6151 thisMBB->addSuccessor(sinkMBB, /* weight */ 1); 6152 6153 // mainMBB: 6154 // mainDstReg = 0 6155 MIB = BuildMI(mainMBB, DL, 6156 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 6157 6158 // Store IP 6159 if (PPCSubTarget.isPPC64()) { 6160 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 6161 .addReg(LabelReg) 6162 .addImm(LabelOffset) 6163 .addReg(BufReg); 6164 } else { 6165 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 6166 .addReg(LabelReg) 6167 .addImm(LabelOffset) 6168 .addReg(BufReg); 6169 } 6170 6171 MIB.setMemRefs(MMOBegin, MMOEnd); 6172 6173 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 6174 mainMBB->addSuccessor(sinkMBB); 6175 6176 // sinkMBB: 6177 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 6178 TII->get(PPC::PHI), DstReg) 6179 .addReg(mainDstReg).addMBB(mainMBB) 6180 .addReg(restoreDstReg).addMBB(thisMBB); 6181 6182 MI->eraseFromParent(); 6183 return sinkMBB; 6184 } 6185 6186 MachineBasicBlock * 6187 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI, 6188 MachineBasicBlock *MBB) const { 6189 DebugLoc DL = MI->getDebugLoc(); 6190 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6191 6192 MachineFunction *MF = MBB->getParent(); 6193 MachineRegisterInfo &MRI = MF->getRegInfo(); 6194 6195 // Memory Reference 6196 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 6197 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 6198 6199 MVT PVT = getPointerTy(); 6200 assert((PVT == MVT::i64 || PVT == MVT::i32) && 6201 "Invalid Pointer Size!"); 6202 6203 const TargetRegisterClass *RC = 6204 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6205 unsigned Tmp = MRI.createVirtualRegister(RC); 6206 // Since FP is only updated here but NOT referenced, it's treated as GPR. 6207 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 6208 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 6209 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30; 6210 6211 MachineInstrBuilder MIB; 6212 6213 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 6214 const int64_t SPOffset = 2 * PVT.getStoreSize(); 6215 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 6216 const int64_t BPOffset = 4 * PVT.getStoreSize(); 6217 6218 unsigned BufReg = MI->getOperand(0).getReg(); 6219 6220 // Reload FP (the jumped-to function may not have had a 6221 // frame pointer, and if so, then its r31 will be restored 6222 // as necessary). 6223 if (PVT == MVT::i64) { 6224 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 6225 .addImm(0) 6226 .addReg(BufReg); 6227 } else { 6228 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 6229 .addImm(0) 6230 .addReg(BufReg); 6231 } 6232 MIB.setMemRefs(MMOBegin, MMOEnd); 6233 6234 // Reload IP 6235 if (PVT == MVT::i64) { 6236 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 6237 .addImm(LabelOffset) 6238 .addReg(BufReg); 6239 } else { 6240 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 6241 .addImm(LabelOffset) 6242 .addReg(BufReg); 6243 } 6244 MIB.setMemRefs(MMOBegin, MMOEnd); 6245 6246 // Reload SP 6247 if (PVT == MVT::i64) { 6248 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 6249 .addImm(SPOffset) 6250 .addReg(BufReg); 6251 } else { 6252 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 6253 .addImm(SPOffset) 6254 .addReg(BufReg); 6255 } 6256 MIB.setMemRefs(MMOBegin, MMOEnd); 6257 6258 // Reload BP 6259 if (PVT == MVT::i64) { 6260 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 6261 .addImm(BPOffset) 6262 .addReg(BufReg); 6263 } else { 6264 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 6265 .addImm(BPOffset) 6266 .addReg(BufReg); 6267 } 6268 MIB.setMemRefs(MMOBegin, MMOEnd); 6269 6270 // Reload TOC 6271 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) { 6272 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 6273 .addImm(TOCOffset) 6274 .addReg(BufReg); 6275 6276 MIB.setMemRefs(MMOBegin, MMOEnd); 6277 } 6278 6279 // Jump 6280 BuildMI(*MBB, MI, DL, 6281 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 6282 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 6283 6284 MI->eraseFromParent(); 6285 return MBB; 6286 } 6287 6288 MachineBasicBlock * 6289 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 6290 MachineBasicBlock *BB) const { 6291 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 || 6292 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) { 6293 return emitEHSjLjSetJmp(MI, BB); 6294 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 || 6295 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) { 6296 return emitEHSjLjLongJmp(MI, BB); 6297 } 6298 6299 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6300 6301 // To "insert" these instructions we actually have to insert their 6302 // control-flow patterns. 6303 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 6304 MachineFunction::iterator It = BB; 6305 ++It; 6306 6307 MachineFunction *F = BB->getParent(); 6308 6309 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 || 6310 MI->getOpcode() == PPC::SELECT_CC_I8)) { 6311 SmallVector<MachineOperand, 2> Cond; 6312 Cond.push_back(MI->getOperand(4)); 6313 Cond.push_back(MI->getOperand(1)); 6314 6315 DebugLoc dl = MI->getDebugLoc(); 6316 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6317 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(), 6318 Cond, MI->getOperand(2).getReg(), 6319 MI->getOperand(3).getReg()); 6320 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 || 6321 MI->getOpcode() == PPC::SELECT_CC_I8 || 6322 MI->getOpcode() == PPC::SELECT_CC_F4 || 6323 MI->getOpcode() == PPC::SELECT_CC_F8 || 6324 MI->getOpcode() == PPC::SELECT_CC_VRRC) { 6325 6326 6327 // The incoming instruction knows the destination vreg to set, the 6328 // condition code register to branch on, the true/false values to 6329 // select between, and a branch opcode to use. 6330 6331 // thisMBB: 6332 // ... 6333 // TrueVal = ... 6334 // cmpTY ccX, r1, r2 6335 // bCC copy1MBB 6336 // fallthrough --> copy0MBB 6337 MachineBasicBlock *thisMBB = BB; 6338 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 6339 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 6340 unsigned SelectPred = MI->getOperand(4).getImm(); 6341 DebugLoc dl = MI->getDebugLoc(); 6342 F->insert(It, copy0MBB); 6343 F->insert(It, sinkMBB); 6344 6345 // Transfer the remainder of BB and its successor edges to sinkMBB. 6346 sinkMBB->splice(sinkMBB->begin(), BB, 6347 llvm::next(MachineBasicBlock::iterator(MI)), 6348 BB->end()); 6349 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 6350 6351 // Next, add the true and fallthrough blocks as its successors. 6352 BB->addSuccessor(copy0MBB); 6353 BB->addSuccessor(sinkMBB); 6354 6355 BuildMI(BB, dl, TII->get(PPC::BCC)) 6356 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB); 6357 6358 // copy0MBB: 6359 // %FalseValue = ... 6360 // # fallthrough to sinkMBB 6361 BB = copy0MBB; 6362 6363 // Update machine-CFG edges 6364 BB->addSuccessor(sinkMBB); 6365 6366 // sinkMBB: 6367 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 6368 // ... 6369 BB = sinkMBB; 6370 BuildMI(*BB, BB->begin(), dl, 6371 TII->get(PPC::PHI), MI->getOperand(0).getReg()) 6372 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB) 6373 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 6374 } 6375 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 6376 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 6377 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 6378 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 6379 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 6380 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4); 6381 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 6382 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8); 6383 6384 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 6385 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 6386 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 6387 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 6388 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 6389 BB = EmitAtomicBinary(MI, BB, false, PPC::AND); 6390 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 6391 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8); 6392 6393 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 6394 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 6395 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 6396 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 6397 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 6398 BB = EmitAtomicBinary(MI, BB, false, PPC::OR); 6399 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 6400 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8); 6401 6402 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 6403 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 6404 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 6405 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 6406 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 6407 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR); 6408 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 6409 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8); 6410 6411 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 6412 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC); 6413 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 6414 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC); 6415 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 6416 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC); 6417 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 6418 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8); 6419 6420 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 6421 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 6422 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 6423 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 6424 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 6425 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF); 6426 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 6427 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8); 6428 6429 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8) 6430 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 6431 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16) 6432 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 6433 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32) 6434 BB = EmitAtomicBinary(MI, BB, false, 0); 6435 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64) 6436 BB = EmitAtomicBinary(MI, BB, true, 0); 6437 6438 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 6439 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) { 6440 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 6441 6442 unsigned dest = MI->getOperand(0).getReg(); 6443 unsigned ptrA = MI->getOperand(1).getReg(); 6444 unsigned ptrB = MI->getOperand(2).getReg(); 6445 unsigned oldval = MI->getOperand(3).getReg(); 6446 unsigned newval = MI->getOperand(4).getReg(); 6447 DebugLoc dl = MI->getDebugLoc(); 6448 6449 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 6450 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 6451 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 6452 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 6453 F->insert(It, loop1MBB); 6454 F->insert(It, loop2MBB); 6455 F->insert(It, midMBB); 6456 F->insert(It, exitMBB); 6457 exitMBB->splice(exitMBB->begin(), BB, 6458 llvm::next(MachineBasicBlock::iterator(MI)), 6459 BB->end()); 6460 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 6461 6462 // thisMBB: 6463 // ... 6464 // fallthrough --> loopMBB 6465 BB->addSuccessor(loop1MBB); 6466 6467 // loop1MBB: 6468 // l[wd]arx dest, ptr 6469 // cmp[wd] dest, oldval 6470 // bne- midMBB 6471 // loop2MBB: 6472 // st[wd]cx. newval, ptr 6473 // bne- loopMBB 6474 // b exitBB 6475 // midMBB: 6476 // st[wd]cx. dest, ptr 6477 // exitBB: 6478 BB = loop1MBB; 6479 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest) 6480 .addReg(ptrA).addReg(ptrB); 6481 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 6482 .addReg(oldval).addReg(dest); 6483 BuildMI(BB, dl, TII->get(PPC::BCC)) 6484 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 6485 BB->addSuccessor(loop2MBB); 6486 BB->addSuccessor(midMBB); 6487 6488 BB = loop2MBB; 6489 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 6490 .addReg(newval).addReg(ptrA).addReg(ptrB); 6491 BuildMI(BB, dl, TII->get(PPC::BCC)) 6492 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 6493 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 6494 BB->addSuccessor(loop1MBB); 6495 BB->addSuccessor(exitMBB); 6496 6497 BB = midMBB; 6498 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 6499 .addReg(dest).addReg(ptrA).addReg(ptrB); 6500 BB->addSuccessor(exitMBB); 6501 6502 // exitMBB: 6503 // ... 6504 BB = exitMBB; 6505 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 6506 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 6507 // We must use 64-bit registers for addresses when targeting 64-bit, 6508 // since we're actually doing arithmetic on them. Other registers 6509 // can be 32-bit. 6510 bool is64bit = PPCSubTarget.isPPC64(); 6511 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 6512 6513 unsigned dest = MI->getOperand(0).getReg(); 6514 unsigned ptrA = MI->getOperand(1).getReg(); 6515 unsigned ptrB = MI->getOperand(2).getReg(); 6516 unsigned oldval = MI->getOperand(3).getReg(); 6517 unsigned newval = MI->getOperand(4).getReg(); 6518 DebugLoc dl = MI->getDebugLoc(); 6519 6520 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 6521 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 6522 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 6523 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 6524 F->insert(It, loop1MBB); 6525 F->insert(It, loop2MBB); 6526 F->insert(It, midMBB); 6527 F->insert(It, exitMBB); 6528 exitMBB->splice(exitMBB->begin(), BB, 6529 llvm::next(MachineBasicBlock::iterator(MI)), 6530 BB->end()); 6531 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 6532 6533 MachineRegisterInfo &RegInfo = F->getRegInfo(); 6534 const TargetRegisterClass *RC = 6535 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass : 6536 (const TargetRegisterClass *) &PPC::GPRCRegClass; 6537 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 6538 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 6539 unsigned ShiftReg = RegInfo.createVirtualRegister(RC); 6540 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 6541 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 6542 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 6543 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 6544 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 6545 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 6546 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 6547 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 6548 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 6549 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 6550 unsigned Ptr1Reg; 6551 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 6552 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 6553 // thisMBB: 6554 // ... 6555 // fallthrough --> loopMBB 6556 BB->addSuccessor(loop1MBB); 6557 6558 // The 4-byte load must be aligned, while a char or short may be 6559 // anywhere in the word. Hence all this nasty bookkeeping code. 6560 // add ptr1, ptrA, ptrB [copy if ptrA==0] 6561 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 6562 // xori shift, shift1, 24 [16] 6563 // rlwinm ptr, ptr1, 0, 0, 29 6564 // slw newval2, newval, shift 6565 // slw oldval2, oldval,shift 6566 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 6567 // slw mask, mask2, shift 6568 // and newval3, newval2, mask 6569 // and oldval3, oldval2, mask 6570 // loop1MBB: 6571 // lwarx tmpDest, ptr 6572 // and tmp, tmpDest, mask 6573 // cmpw tmp, oldval3 6574 // bne- midMBB 6575 // loop2MBB: 6576 // andc tmp2, tmpDest, mask 6577 // or tmp4, tmp2, newval3 6578 // stwcx. tmp4, ptr 6579 // bne- loop1MBB 6580 // b exitBB 6581 // midMBB: 6582 // stwcx. tmpDest, ptr 6583 // exitBB: 6584 // srw dest, tmpDest, shift 6585 if (ptrA != ZeroReg) { 6586 Ptr1Reg = RegInfo.createVirtualRegister(RC); 6587 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 6588 .addReg(ptrA).addReg(ptrB); 6589 } else { 6590 Ptr1Reg = ptrB; 6591 } 6592 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 6593 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 6594 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 6595 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 6596 if (is64bit) 6597 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 6598 .addReg(Ptr1Reg).addImm(0).addImm(61); 6599 else 6600 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 6601 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 6602 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 6603 .addReg(newval).addReg(ShiftReg); 6604 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 6605 .addReg(oldval).addReg(ShiftReg); 6606 if (is8bit) 6607 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 6608 else { 6609 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 6610 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 6611 .addReg(Mask3Reg).addImm(65535); 6612 } 6613 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 6614 .addReg(Mask2Reg).addReg(ShiftReg); 6615 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 6616 .addReg(NewVal2Reg).addReg(MaskReg); 6617 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 6618 .addReg(OldVal2Reg).addReg(MaskReg); 6619 6620 BB = loop1MBB; 6621 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 6622 .addReg(ZeroReg).addReg(PtrReg); 6623 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 6624 .addReg(TmpDestReg).addReg(MaskReg); 6625 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 6626 .addReg(TmpReg).addReg(OldVal3Reg); 6627 BuildMI(BB, dl, TII->get(PPC::BCC)) 6628 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 6629 BB->addSuccessor(loop2MBB); 6630 BB->addSuccessor(midMBB); 6631 6632 BB = loop2MBB; 6633 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 6634 .addReg(TmpDestReg).addReg(MaskReg); 6635 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 6636 .addReg(Tmp2Reg).addReg(NewVal3Reg); 6637 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 6638 .addReg(ZeroReg).addReg(PtrReg); 6639 BuildMI(BB, dl, TII->get(PPC::BCC)) 6640 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 6641 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 6642 BB->addSuccessor(loop1MBB); 6643 BB->addSuccessor(exitMBB); 6644 6645 BB = midMBB; 6646 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 6647 .addReg(ZeroReg).addReg(PtrReg); 6648 BB->addSuccessor(exitMBB); 6649 6650 // exitMBB: 6651 // ... 6652 BB = exitMBB; 6653 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 6654 .addReg(ShiftReg); 6655 } else if (MI->getOpcode() == PPC::FADDrtz) { 6656 // This pseudo performs an FADD with rounding mode temporarily forced 6657 // to round-to-zero. We emit this via custom inserter since the FPSCR 6658 // is not modeled at the SelectionDAG level. 6659 unsigned Dest = MI->getOperand(0).getReg(); 6660 unsigned Src1 = MI->getOperand(1).getReg(); 6661 unsigned Src2 = MI->getOperand(2).getReg(); 6662 DebugLoc dl = MI->getDebugLoc(); 6663 6664 MachineRegisterInfo &RegInfo = F->getRegInfo(); 6665 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 6666 6667 // Save FPSCR value. 6668 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 6669 6670 // Set rounding mode to round-to-zero. 6671 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 6672 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 6673 6674 // Perform addition. 6675 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 6676 6677 // Restore FPSCR value. 6678 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg); 6679 } else if (MI->getOpcode() == PPC::FRINDrint || 6680 MI->getOpcode() == PPC::FRINSrint) { 6681 bool isf32 = MI->getOpcode() == PPC::FRINSrint; 6682 unsigned Dest = MI->getOperand(0).getReg(); 6683 unsigned Src = MI->getOperand(1).getReg(); 6684 DebugLoc dl = MI->getDebugLoc(); 6685 6686 MachineRegisterInfo &RegInfo = F->getRegInfo(); 6687 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 6688 6689 // Perform the rounding. 6690 BuildMI(*BB, MI, dl, TII->get(isf32 ? PPC::FRINS : PPC::FRIND), Dest) 6691 .addReg(Src); 6692 6693 // Compare the results. 6694 BuildMI(*BB, MI, dl, TII->get(isf32 ? PPC::FCMPUS : PPC::FCMPUD), CRReg) 6695 .addReg(Dest).addReg(Src); 6696 6697 // If the results were not equal, then set the FPSCR XX bit. 6698 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 6699 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 6700 F->insert(It, midMBB); 6701 F->insert(It, exitMBB); 6702 exitMBB->splice(exitMBB->begin(), BB, 6703 llvm::next(MachineBasicBlock::iterator(MI)), 6704 BB->end()); 6705 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 6706 6707 BuildMI(*BB, MI, dl, TII->get(PPC::BCC)) 6708 .addImm(PPC::PRED_EQ).addReg(CRReg).addMBB(exitMBB); 6709 6710 BB->addSuccessor(midMBB); 6711 BB->addSuccessor(exitMBB); 6712 6713 BB = midMBB; 6714 6715 // Set the FPSCR XX bit (FE_INEXACT). Note that we cannot just set 6716 // the FI bit here because that will not automatically set XX also, 6717 // and XX is what libm interprets as the FE_INEXACT flag. 6718 BuildMI(BB, dl, TII->get(PPC::MTFSB1)).addImm(/* 38 - 32 = */ 6); 6719 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 6720 6721 BB->addSuccessor(exitMBB); 6722 6723 BB = exitMBB; 6724 } else { 6725 llvm_unreachable("Unexpected instr type to insert"); 6726 } 6727 6728 MI->eraseFromParent(); // The pseudo instruction is gone now. 6729 return BB; 6730 } 6731 6732 //===----------------------------------------------------------------------===// 6733 // Target Optimization Hooks 6734 //===----------------------------------------------------------------------===// 6735 6736 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op, 6737 DAGCombinerInfo &DCI) const { 6738 if (DCI.isAfterLegalizeVectorOps()) 6739 return SDValue(); 6740 6741 EVT VT = Op.getValueType(); 6742 6743 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) || 6744 (VT == MVT::f64 && PPCSubTarget.hasFRE()) || 6745 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) { 6746 6747 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 6748 // For the reciprocal, we need to find the zero of the function: 6749 // F(X) = A X - 1 [which has a zero at X = 1/A] 6750 // => 6751 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 6752 // does not require additional intermediate precision] 6753 6754 // Convergence is quadratic, so we essentially double the number of digits 6755 // correct after every iteration. The minimum architected relative 6756 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has 6757 // 23 digits and double has 52 digits. 6758 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3; 6759 if (VT.getScalarType() == MVT::f64) 6760 ++Iterations; 6761 6762 SelectionDAG &DAG = DCI.DAG; 6763 SDLoc dl(Op); 6764 6765 SDValue FPOne = 6766 DAG.getConstantFP(1.0, VT.getScalarType()); 6767 if (VT.isVector()) { 6768 assert(VT.getVectorNumElements() == 4 && 6769 "Unknown vector type"); 6770 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, 6771 FPOne, FPOne, FPOne, FPOne); 6772 } 6773 6774 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op); 6775 DCI.AddToWorklist(Est.getNode()); 6776 6777 // Newton iterations: Est = Est + Est (1 - Arg * Est) 6778 for (int i = 0; i < Iterations; ++i) { 6779 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est); 6780 DCI.AddToWorklist(NewEst.getNode()); 6781 6782 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst); 6783 DCI.AddToWorklist(NewEst.getNode()); 6784 6785 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst); 6786 DCI.AddToWorklist(NewEst.getNode()); 6787 6788 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst); 6789 DCI.AddToWorklist(Est.getNode()); 6790 } 6791 6792 return Est; 6793 } 6794 6795 return SDValue(); 6796 } 6797 6798 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op, 6799 DAGCombinerInfo &DCI) const { 6800 if (DCI.isAfterLegalizeVectorOps()) 6801 return SDValue(); 6802 6803 EVT VT = Op.getValueType(); 6804 6805 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) || 6806 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) || 6807 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) { 6808 6809 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 6810 // For the reciprocal sqrt, we need to find the zero of the function: 6811 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 6812 // => 6813 // X_{i+1} = X_i (1.5 - A X_i^2 / 2) 6814 // As a result, we precompute A/2 prior to the iteration loop. 6815 6816 // Convergence is quadratic, so we essentially double the number of digits 6817 // correct after every iteration. The minimum architected relative 6818 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has 6819 // 23 digits and double has 52 digits. 6820 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3; 6821 if (VT.getScalarType() == MVT::f64) 6822 ++Iterations; 6823 6824 SelectionDAG &DAG = DCI.DAG; 6825 SDLoc dl(Op); 6826 6827 SDValue FPThreeHalves = 6828 DAG.getConstantFP(1.5, VT.getScalarType()); 6829 if (VT.isVector()) { 6830 assert(VT.getVectorNumElements() == 4 && 6831 "Unknown vector type"); 6832 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, 6833 FPThreeHalves, FPThreeHalves, 6834 FPThreeHalves, FPThreeHalves); 6835 } 6836 6837 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op); 6838 DCI.AddToWorklist(Est.getNode()); 6839 6840 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that 6841 // this entire sequence requires only one FP constant. 6842 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op); 6843 DCI.AddToWorklist(HalfArg.getNode()); 6844 6845 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op); 6846 DCI.AddToWorklist(HalfArg.getNode()); 6847 6848 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 6849 for (int i = 0; i < Iterations; ++i) { 6850 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est); 6851 DCI.AddToWorklist(NewEst.getNode()); 6852 6853 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst); 6854 DCI.AddToWorklist(NewEst.getNode()); 6855 6856 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst); 6857 DCI.AddToWorklist(NewEst.getNode()); 6858 6859 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst); 6860 DCI.AddToWorklist(Est.getNode()); 6861 } 6862 6863 return Est; 6864 } 6865 6866 return SDValue(); 6867 } 6868 6869 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 6870 // not enforce equality of the chain operands. 6871 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base, 6872 unsigned Bytes, int Dist, 6873 SelectionDAG &DAG) { 6874 EVT VT = LS->getMemoryVT(); 6875 if (VT.getSizeInBits() / 8 != Bytes) 6876 return false; 6877 6878 SDValue Loc = LS->getBasePtr(); 6879 SDValue BaseLoc = Base->getBasePtr(); 6880 if (Loc.getOpcode() == ISD::FrameIndex) { 6881 if (BaseLoc.getOpcode() != ISD::FrameIndex) 6882 return false; 6883 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 6884 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 6885 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 6886 int FS = MFI->getObjectSize(FI); 6887 int BFS = MFI->getObjectSize(BFI); 6888 if (FS != BFS || FS != (int)Bytes) return false; 6889 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes); 6890 } 6891 6892 // Handle X+C 6893 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc && 6894 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes) 6895 return true; 6896 6897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6898 const GlobalValue *GV1 = NULL; 6899 const GlobalValue *GV2 = NULL; 6900 int64_t Offset1 = 0; 6901 int64_t Offset2 = 0; 6902 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 6903 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 6904 if (isGA1 && isGA2 && GV1 == GV2) 6905 return Offset1 == (Offset2 + Dist*Bytes); 6906 return false; 6907 } 6908 6909 // Return true is there is a nearyby consecutive load to the one provided 6910 // (regardless of alignment). We search up and down the chain, looking though 6911 // token factors and other loads (but nothing else). As a result, a true 6912 // results indicates that it is safe to create a new consecutive load adjacent 6913 // to the load provided. 6914 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 6915 SDValue Chain = LD->getChain(); 6916 EVT VT = LD->getMemoryVT(); 6917 6918 SmallSet<SDNode *, 16> LoadRoots; 6919 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 6920 SmallSet<SDNode *, 16> Visited; 6921 6922 // First, search up the chain, branching to follow all token-factor operands. 6923 // If we find a consecutive load, then we're done, otherwise, record all 6924 // nodes just above the top-level loads and token factors. 6925 while (!Queue.empty()) { 6926 SDNode *ChainNext = Queue.pop_back_val(); 6927 if (!Visited.insert(ChainNext)) 6928 continue; 6929 6930 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) { 6931 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 6932 return true; 6933 6934 if (!Visited.count(ChainLD->getChain().getNode())) 6935 Queue.push_back(ChainLD->getChain().getNode()); 6936 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 6937 for (SDNode::op_iterator O = ChainNext->op_begin(), 6938 OE = ChainNext->op_end(); O != OE; ++O) 6939 if (!Visited.count(O->getNode())) 6940 Queue.push_back(O->getNode()); 6941 } else 6942 LoadRoots.insert(ChainNext); 6943 } 6944 6945 // Second, search down the chain, starting from the top-level nodes recorded 6946 // in the first phase. These top-level nodes are the nodes just above all 6947 // loads and token factors. Starting with their uses, recursively look though 6948 // all loads (just the chain uses) and token factors to find a consecutive 6949 // load. 6950 Visited.clear(); 6951 Queue.clear(); 6952 6953 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 6954 IE = LoadRoots.end(); I != IE; ++I) { 6955 Queue.push_back(*I); 6956 6957 while (!Queue.empty()) { 6958 SDNode *LoadRoot = Queue.pop_back_val(); 6959 if (!Visited.insert(LoadRoot)) 6960 continue; 6961 6962 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot)) 6963 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 6964 return true; 6965 6966 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 6967 UE = LoadRoot->use_end(); UI != UE; ++UI) 6968 if (((isa<LoadSDNode>(*UI) && 6969 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) || 6970 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 6971 Queue.push_back(*UI); 6972 } 6973 } 6974 6975 return false; 6976 } 6977 6978 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 6979 DAGCombinerInfo &DCI) const { 6980 const TargetMachine &TM = getTargetMachine(); 6981 SelectionDAG &DAG = DCI.DAG; 6982 SDLoc dl(N); 6983 switch (N->getOpcode()) { 6984 default: break; 6985 case PPCISD::SHL: 6986 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 6987 if (C->isNullValue()) // 0 << V -> 0. 6988 return N->getOperand(0); 6989 } 6990 break; 6991 case PPCISD::SRL: 6992 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 6993 if (C->isNullValue()) // 0 >>u V -> 0. 6994 return N->getOperand(0); 6995 } 6996 break; 6997 case PPCISD::SRA: 6998 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 6999 if (C->isNullValue() || // 0 >>s V -> 0. 7000 C->isAllOnesValue()) // -1 >>s V -> -1. 7001 return N->getOperand(0); 7002 } 7003 break; 7004 case ISD::FDIV: { 7005 assert(TM.Options.UnsafeFPMath && 7006 "Reciprocal estimates require UnsafeFPMath"); 7007 7008 if (N->getOperand(1).getOpcode() == ISD::FSQRT) { 7009 SDValue RV = 7010 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI); 7011 if (RV.getNode() != 0) { 7012 DCI.AddToWorklist(RV.getNode()); 7013 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0), 7014 N->getOperand(0), RV); 7015 } 7016 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND && 7017 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) { 7018 SDValue RV = 7019 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0), 7020 DCI); 7021 if (RV.getNode() != 0) { 7022 DCI.AddToWorklist(RV.getNode()); 7023 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)), 7024 N->getValueType(0), RV); 7025 DCI.AddToWorklist(RV.getNode()); 7026 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0), 7027 N->getOperand(0), RV); 7028 } 7029 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND && 7030 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) { 7031 SDValue RV = 7032 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0), 7033 DCI); 7034 if (RV.getNode() != 0) { 7035 DCI.AddToWorklist(RV.getNode()); 7036 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)), 7037 N->getValueType(0), RV, 7038 N->getOperand(1).getOperand(1)); 7039 DCI.AddToWorklist(RV.getNode()); 7040 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0), 7041 N->getOperand(0), RV); 7042 } 7043 } 7044 7045 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI); 7046 if (RV.getNode() != 0) { 7047 DCI.AddToWorklist(RV.getNode()); 7048 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0), 7049 N->getOperand(0), RV); 7050 } 7051 7052 } 7053 break; 7054 case ISD::FSQRT: { 7055 assert(TM.Options.UnsafeFPMath && 7056 "Reciprocal estimates require UnsafeFPMath"); 7057 7058 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the 7059 // reciprocal sqrt. 7060 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI); 7061 if (RV.getNode() != 0) { 7062 DCI.AddToWorklist(RV.getNode()); 7063 RV = DAGCombineFastRecip(RV, DCI); 7064 if (RV.getNode() != 0) 7065 return RV; 7066 } 7067 7068 } 7069 break; 7070 case ISD::SINT_TO_FP: 7071 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) { 7072 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) { 7073 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores. 7074 // We allow the src/dst to be either f32/f64, but the intermediate 7075 // type must be i64. 7076 if (N->getOperand(0).getValueType() == MVT::i64 && 7077 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) { 7078 SDValue Val = N->getOperand(0).getOperand(0); 7079 if (Val.getValueType() == MVT::f32) { 7080 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 7081 DCI.AddToWorklist(Val.getNode()); 7082 } 7083 7084 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val); 7085 DCI.AddToWorklist(Val.getNode()); 7086 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val); 7087 DCI.AddToWorklist(Val.getNode()); 7088 if (N->getValueType(0) == MVT::f32) { 7089 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val, 7090 DAG.getIntPtrConstant(0)); 7091 DCI.AddToWorklist(Val.getNode()); 7092 } 7093 return Val; 7094 } else if (N->getOperand(0).getValueType() == MVT::i32) { 7095 // If the intermediate type is i32, we can avoid the load/store here 7096 // too. 7097 } 7098 } 7099 } 7100 break; 7101 case ISD::STORE: 7102 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 7103 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() && 7104 !cast<StoreSDNode>(N)->isTruncatingStore() && 7105 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 7106 N->getOperand(1).getValueType() == MVT::i32 && 7107 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 7108 SDValue Val = N->getOperand(1).getOperand(0); 7109 if (Val.getValueType() == MVT::f32) { 7110 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 7111 DCI.AddToWorklist(Val.getNode()); 7112 } 7113 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 7114 DCI.AddToWorklist(Val.getNode()); 7115 7116 SDValue Ops[] = { 7117 N->getOperand(0), Val, N->getOperand(2), 7118 DAG.getValueType(N->getOperand(1).getValueType()) 7119 }; 7120 7121 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7122 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops), 7123 cast<StoreSDNode>(N)->getMemoryVT(), 7124 cast<StoreSDNode>(N)->getMemOperand()); 7125 DCI.AddToWorklist(Val.getNode()); 7126 return Val; 7127 } 7128 7129 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 7130 if (cast<StoreSDNode>(N)->isUnindexed() && 7131 N->getOperand(1).getOpcode() == ISD::BSWAP && 7132 N->getOperand(1).getNode()->hasOneUse() && 7133 (N->getOperand(1).getValueType() == MVT::i32 || 7134 N->getOperand(1).getValueType() == MVT::i16 || 7135 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() && 7136 TM.getSubtarget<PPCSubtarget>().isPPC64() && 7137 N->getOperand(1).getValueType() == MVT::i64))) { 7138 SDValue BSwapOp = N->getOperand(1).getOperand(0); 7139 // Do an any-extend to 32-bits if this is a half-word input. 7140 if (BSwapOp.getValueType() == MVT::i16) 7141 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 7142 7143 SDValue Ops[] = { 7144 N->getOperand(0), BSwapOp, N->getOperand(2), 7145 DAG.getValueType(N->getOperand(1).getValueType()) 7146 }; 7147 return 7148 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 7149 Ops, array_lengthof(Ops), 7150 cast<StoreSDNode>(N)->getMemoryVT(), 7151 cast<StoreSDNode>(N)->getMemOperand()); 7152 } 7153 break; 7154 case ISD::LOAD: { 7155 LoadSDNode *LD = cast<LoadSDNode>(N); 7156 EVT VT = LD->getValueType(0); 7157 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext()); 7158 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty); 7159 if (ISD::isNON_EXTLoad(N) && VT.isVector() && 7160 TM.getSubtarget<PPCSubtarget>().hasAltivec() && 7161 DCI.getDAGCombineLevel() == AfterLegalizeTypes && 7162 LD->getAlignment() < ABIAlignment) { 7163 // This is a type-legal unaligned Altivec load. 7164 SDValue Chain = LD->getChain(); 7165 SDValue Ptr = LD->getBasePtr(); 7166 7167 // This implements the loading of unaligned vectors as described in 7168 // the venerable Apple Velocity Engine overview. Specifically: 7169 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 7170 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 7171 // 7172 // The general idea is to expand a sequence of one or more unaligned 7173 // loads into a alignment-based permutation-control instruction (lvsl), 7174 // a series of regular vector loads (which always truncate their 7175 // input address to an aligned address), and a series of permutations. 7176 // The results of these permutations are the requested loaded values. 7177 // The trick is that the last "extra" load is not taken from the address 7178 // you might suspect (sizeof(vector) bytes after the last requested 7179 // load), but rather sizeof(vector) - 1 bytes after the last 7180 // requested vector. The point of this is to avoid a page fault if the 7181 // base address happend to be aligned. This works because if the base 7182 // address is aligned, then adding less than a full vector length will 7183 // cause the last vector in the sequence to be (re)loaded. Otherwise, 7184 // the next vector will be fetched as you might suspect was necessary. 7185 7186 // We might be able to reuse the permutation generation from 7187 // a different base address offset from this one by an aligned amount. 7188 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 7189 // optimization later. 7190 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr, 7191 DAG, dl, MVT::v16i8); 7192 7193 // Refine the alignment of the original load (a "new" load created here 7194 // which was identical to the first except for the alignment would be 7195 // merged with the existing node regardless). 7196 MachineFunction &MF = DAG.getMachineFunction(); 7197 MachineMemOperand *MMO = 7198 MF.getMachineMemOperand(LD->getPointerInfo(), 7199 LD->getMemOperand()->getFlags(), 7200 LD->getMemoryVT().getStoreSize(), 7201 ABIAlignment); 7202 LD->refineAlignment(MMO); 7203 SDValue BaseLoad = SDValue(LD, 0); 7204 7205 // Note that the value of IncOffset (which is provided to the next 7206 // load's pointer info offset value, and thus used to calculate the 7207 // alignment), and the value of IncValue (which is actually used to 7208 // increment the pointer value) are different! This is because we 7209 // require the next load to appear to be aligned, even though it 7210 // is actually offset from the base pointer by a lesser amount. 7211 int IncOffset = VT.getSizeInBits() / 8; 7212 int IncValue = IncOffset; 7213 7214 // Walk (both up and down) the chain looking for another load at the real 7215 // (aligned) offset (the alignment of the other load does not matter in 7216 // this case). If found, then do not use the offset reduction trick, as 7217 // that will prevent the loads from being later combined (as they would 7218 // otherwise be duplicates). 7219 if (!findConsecutiveLoad(LD, DAG)) 7220 --IncValue; 7221 7222 SDValue Increment = DAG.getConstant(IncValue, getPointerTy()); 7223 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 7224 7225 SDValue ExtraLoad = 7226 DAG.getLoad(VT, dl, Chain, Ptr, 7227 LD->getPointerInfo().getWithOffset(IncOffset), 7228 LD->isVolatile(), LD->isNonTemporal(), 7229 LD->isInvariant(), ABIAlignment); 7230 7231 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7232 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 7233 7234 if (BaseLoad.getValueType() != MVT::v4i32) 7235 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad); 7236 7237 if (ExtraLoad.getValueType() != MVT::v4i32) 7238 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad); 7239 7240 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm, 7241 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 7242 7243 if (VT != MVT::v4i32) 7244 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm); 7245 7246 // Now we need to be really careful about how we update the users of the 7247 // original load. We cannot just call DCI.CombineTo (or 7248 // DAG.ReplaceAllUsesWith for that matter), because the load still has 7249 // uses created here (the permutation for example) that need to stay. 7250 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 7251 while (UI != UE) { 7252 SDUse &Use = UI.getUse(); 7253 SDNode *User = *UI; 7254 // Note: BaseLoad is checked here because it might not be N, but a 7255 // bitcast of N. 7256 if (User == Perm.getNode() || User == BaseLoad.getNode() || 7257 User == TF.getNode() || Use.getResNo() > 1) { 7258 ++UI; 7259 continue; 7260 } 7261 7262 SDValue To = Use.getResNo() ? TF : Perm; 7263 ++UI; 7264 7265 SmallVector<SDValue, 8> Ops; 7266 for (SDNode::op_iterator O = User->op_begin(), 7267 OE = User->op_end(); O != OE; ++O) { 7268 if (*O == Use) 7269 Ops.push_back(To); 7270 else 7271 Ops.push_back(*O); 7272 } 7273 7274 DAG.UpdateNodeOperands(User, Ops.data(), Ops.size()); 7275 } 7276 7277 return SDValue(N, 0); 7278 } 7279 } 7280 break; 7281 case ISD::INTRINSIC_WO_CHAIN: 7282 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == 7283 Intrinsic::ppc_altivec_lvsl && 7284 N->getOperand(1)->getOpcode() == ISD::ADD) { 7285 SDValue Add = N->getOperand(1); 7286 7287 if (DAG.MaskedValueIsZero(Add->getOperand(1), 7288 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext( 7289 Add.getValueType().getScalarType().getSizeInBits()))) { 7290 SDNode *BasePtr = Add->getOperand(0).getNode(); 7291 for (SDNode::use_iterator UI = BasePtr->use_begin(), 7292 UE = BasePtr->use_end(); UI != UE; ++UI) { 7293 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 7294 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 7295 Intrinsic::ppc_altivec_lvsl) { 7296 // We've found another LVSL, and this address if an aligned 7297 // multiple of that one. The results will be the same, so use the 7298 // one we've just found instead. 7299 7300 return SDValue(*UI, 0); 7301 } 7302 } 7303 } 7304 } 7305 case ISD::BSWAP: 7306 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 7307 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 7308 N->getOperand(0).hasOneUse() && 7309 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 7310 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() && 7311 TM.getSubtarget<PPCSubtarget>().isPPC64() && 7312 N->getValueType(0) == MVT::i64))) { 7313 SDValue Load = N->getOperand(0); 7314 LoadSDNode *LD = cast<LoadSDNode>(Load); 7315 // Create the byte-swapping load. 7316 SDValue Ops[] = { 7317 LD->getChain(), // Chain 7318 LD->getBasePtr(), // Ptr 7319 DAG.getValueType(N->getValueType(0)) // VT 7320 }; 7321 SDValue BSLoad = 7322 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 7323 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 7324 MVT::i64 : MVT::i32, MVT::Other), 7325 Ops, 3, LD->getMemoryVT(), LD->getMemOperand()); 7326 7327 // If this is an i16 load, insert the truncate. 7328 SDValue ResVal = BSLoad; 7329 if (N->getValueType(0) == MVT::i16) 7330 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 7331 7332 // First, combine the bswap away. This makes the value produced by the 7333 // load dead. 7334 DCI.CombineTo(N, ResVal); 7335 7336 // Next, combine the load away, we give it a bogus result value but a real 7337 // chain result. The result value is dead because the bswap is dead. 7338 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 7339 7340 // Return N so it doesn't get rechecked! 7341 return SDValue(N, 0); 7342 } 7343 7344 break; 7345 case PPCISD::VCMP: { 7346 // If a VCMPo node already exists with exactly the same operands as this 7347 // node, use its result instead of this node (VCMPo computes both a CR6 and 7348 // a normal output). 7349 // 7350 if (!N->getOperand(0).hasOneUse() && 7351 !N->getOperand(1).hasOneUse() && 7352 !N->getOperand(2).hasOneUse()) { 7353 7354 // Scan all of the users of the LHS, looking for VCMPo's that match. 7355 SDNode *VCMPoNode = 0; 7356 7357 SDNode *LHSN = N->getOperand(0).getNode(); 7358 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 7359 UI != E; ++UI) 7360 if (UI->getOpcode() == PPCISD::VCMPo && 7361 UI->getOperand(1) == N->getOperand(1) && 7362 UI->getOperand(2) == N->getOperand(2) && 7363 UI->getOperand(0) == N->getOperand(0)) { 7364 VCMPoNode = *UI; 7365 break; 7366 } 7367 7368 // If there is no VCMPo node, or if the flag value has a single use, don't 7369 // transform this. 7370 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 7371 break; 7372 7373 // Look at the (necessarily single) use of the flag value. If it has a 7374 // chain, this transformation is more complex. Note that multiple things 7375 // could use the value result, which we should ignore. 7376 SDNode *FlagUser = 0; 7377 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 7378 FlagUser == 0; ++UI) { 7379 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 7380 SDNode *User = *UI; 7381 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 7382 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 7383 FlagUser = User; 7384 break; 7385 } 7386 } 7387 } 7388 7389 // If the user is a MFOCRF instruction, we know this is safe. 7390 // Otherwise we give up for right now. 7391 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 7392 return SDValue(VCMPoNode, 0); 7393 } 7394 break; 7395 } 7396 case ISD::BR_CC: { 7397 // If this is a branch on an altivec predicate comparison, lower this so 7398 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 7399 // lowering is done pre-legalize, because the legalizer lowers the predicate 7400 // compare down to code that is difficult to reassemble. 7401 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 7402 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 7403 7404 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 7405 // value. If so, pass-through the AND to get to the intrinsic. 7406 if (LHS.getOpcode() == ISD::AND && 7407 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 7408 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 7409 Intrinsic::ppc_is_decremented_ctr_nonzero && 7410 isa<ConstantSDNode>(LHS.getOperand(1)) && 7411 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()-> 7412 isZero()) 7413 LHS = LHS.getOperand(0); 7414 7415 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 7416 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 7417 Intrinsic::ppc_is_decremented_ctr_nonzero && 7418 isa<ConstantSDNode>(RHS)) { 7419 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 7420 "Counter decrement comparison is not EQ or NE"); 7421 7422 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 7423 bool isBDNZ = (CC == ISD::SETEQ && Val) || 7424 (CC == ISD::SETNE && !Val); 7425 7426 // We now need to make the intrinsic dead (it cannot be instruction 7427 // selected). 7428 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 7429 assert(LHS.getNode()->hasOneUse() && 7430 "Counter decrement has more than one use"); 7431 7432 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 7433 N->getOperand(0), N->getOperand(4)); 7434 } 7435 7436 int CompareOpc; 7437 bool isDot; 7438 7439 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 7440 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 7441 getAltivecCompareInfo(LHS, CompareOpc, isDot)) { 7442 assert(isDot && "Can't compare against a vector result!"); 7443 7444 // If this is a comparison against something other than 0/1, then we know 7445 // that the condition is never/always true. 7446 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 7447 if (Val != 0 && Val != 1) { 7448 if (CC == ISD::SETEQ) // Cond never true, remove branch. 7449 return N->getOperand(0); 7450 // Always !=, turn it into an unconditional branch. 7451 return DAG.getNode(ISD::BR, dl, MVT::Other, 7452 N->getOperand(0), N->getOperand(4)); 7453 } 7454 7455 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 7456 7457 // Create the PPCISD altivec 'dot' comparison node. 7458 SDValue Ops[] = { 7459 LHS.getOperand(2), // LHS of compare 7460 LHS.getOperand(3), // RHS of compare 7461 DAG.getConstant(CompareOpc, MVT::i32) 7462 }; 7463 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 7464 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3); 7465 7466 // Unpack the result based on how the target uses it. 7467 PPC::Predicate CompOpc; 7468 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 7469 default: // Can't happen, don't crash on invalid number though. 7470 case 0: // Branch on the value of the EQ bit of CR6. 7471 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 7472 break; 7473 case 1: // Branch on the inverted value of the EQ bit of CR6. 7474 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 7475 break; 7476 case 2: // Branch on the value of the LT bit of CR6. 7477 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 7478 break; 7479 case 3: // Branch on the inverted value of the LT bit of CR6. 7480 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 7481 break; 7482 } 7483 7484 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 7485 DAG.getConstant(CompOpc, MVT::i32), 7486 DAG.getRegister(PPC::CR6, MVT::i32), 7487 N->getOperand(4), CompNode.getValue(1)); 7488 } 7489 break; 7490 } 7491 } 7492 7493 return SDValue(); 7494 } 7495 7496 //===----------------------------------------------------------------------===// 7497 // Inline Assembly Support 7498 //===----------------------------------------------------------------------===// 7499 7500 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 7501 APInt &KnownZero, 7502 APInt &KnownOne, 7503 const SelectionDAG &DAG, 7504 unsigned Depth) const { 7505 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0); 7506 switch (Op.getOpcode()) { 7507 default: break; 7508 case PPCISD::LBRX: { 7509 // lhbrx is known to have the top bits cleared out. 7510 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 7511 KnownZero = 0xFFFF0000; 7512 break; 7513 } 7514 case ISD::INTRINSIC_WO_CHAIN: { 7515 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 7516 default: break; 7517 case Intrinsic::ppc_altivec_vcmpbfp_p: 7518 case Intrinsic::ppc_altivec_vcmpeqfp_p: 7519 case Intrinsic::ppc_altivec_vcmpequb_p: 7520 case Intrinsic::ppc_altivec_vcmpequh_p: 7521 case Intrinsic::ppc_altivec_vcmpequw_p: 7522 case Intrinsic::ppc_altivec_vcmpgefp_p: 7523 case Intrinsic::ppc_altivec_vcmpgtfp_p: 7524 case Intrinsic::ppc_altivec_vcmpgtsb_p: 7525 case Intrinsic::ppc_altivec_vcmpgtsh_p: 7526 case Intrinsic::ppc_altivec_vcmpgtsw_p: 7527 case Intrinsic::ppc_altivec_vcmpgtub_p: 7528 case Intrinsic::ppc_altivec_vcmpgtuh_p: 7529 case Intrinsic::ppc_altivec_vcmpgtuw_p: 7530 KnownZero = ~1U; // All bits but the low one are known to be zero. 7531 break; 7532 } 7533 } 7534 } 7535 } 7536 7537 7538 /// getConstraintType - Given a constraint, return the type of 7539 /// constraint it is for this target. 7540 PPCTargetLowering::ConstraintType 7541 PPCTargetLowering::getConstraintType(const std::string &Constraint) const { 7542 if (Constraint.size() == 1) { 7543 switch (Constraint[0]) { 7544 default: break; 7545 case 'b': 7546 case 'r': 7547 case 'f': 7548 case 'v': 7549 case 'y': 7550 return C_RegisterClass; 7551 case 'Z': 7552 // FIXME: While Z does indicate a memory constraint, it specifically 7553 // indicates an r+r address (used in conjunction with the 'y' modifier 7554 // in the replacement string). Currently, we're forcing the base 7555 // register to be r0 in the asm printer (which is interpreted as zero) 7556 // and forming the complete address in the second register. This is 7557 // suboptimal. 7558 return C_Memory; 7559 } 7560 } 7561 return TargetLowering::getConstraintType(Constraint); 7562 } 7563 7564 /// Examine constraint type and operand type and determine a weight value. 7565 /// This object must already have been set up with the operand type 7566 /// and the current alternative constraint selected. 7567 TargetLowering::ConstraintWeight 7568 PPCTargetLowering::getSingleConstraintMatchWeight( 7569 AsmOperandInfo &info, const char *constraint) const { 7570 ConstraintWeight weight = CW_Invalid; 7571 Value *CallOperandVal = info.CallOperandVal; 7572 // If we don't have a value, we can't do a match, 7573 // but allow it at the lowest weight. 7574 if (CallOperandVal == NULL) 7575 return CW_Default; 7576 Type *type = CallOperandVal->getType(); 7577 // Look at the constraint type. 7578 switch (*constraint) { 7579 default: 7580 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 7581 break; 7582 case 'b': 7583 if (type->isIntegerTy()) 7584 weight = CW_Register; 7585 break; 7586 case 'f': 7587 if (type->isFloatTy()) 7588 weight = CW_Register; 7589 break; 7590 case 'd': 7591 if (type->isDoubleTy()) 7592 weight = CW_Register; 7593 break; 7594 case 'v': 7595 if (type->isVectorTy()) 7596 weight = CW_Register; 7597 break; 7598 case 'y': 7599 weight = CW_Register; 7600 break; 7601 case 'Z': 7602 weight = CW_Memory; 7603 break; 7604 } 7605 return weight; 7606 } 7607 7608 std::pair<unsigned, const TargetRegisterClass*> 7609 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 7610 MVT VT) const { 7611 if (Constraint.size() == 1) { 7612 // GCC RS6000 Constraint Letters 7613 switch (Constraint[0]) { 7614 case 'b': // R1-R31 7615 if (VT == MVT::i64 && PPCSubTarget.isPPC64()) 7616 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 7617 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 7618 case 'r': // R0-R31 7619 if (VT == MVT::i64 && PPCSubTarget.isPPC64()) 7620 return std::make_pair(0U, &PPC::G8RCRegClass); 7621 return std::make_pair(0U, &PPC::GPRCRegClass); 7622 case 'f': 7623 if (VT == MVT::f32 || VT == MVT::i32) 7624 return std::make_pair(0U, &PPC::F4RCRegClass); 7625 if (VT == MVT::f64 || VT == MVT::i64) 7626 return std::make_pair(0U, &PPC::F8RCRegClass); 7627 break; 7628 case 'v': 7629 return std::make_pair(0U, &PPC::VRRCRegClass); 7630 case 'y': // crrc 7631 return std::make_pair(0U, &PPC::CRRCRegClass); 7632 } 7633 } 7634 7635 std::pair<unsigned, const TargetRegisterClass*> R = 7636 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 7637 7638 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 7639 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 7640 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 7641 // register. 7642 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 7643 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 7644 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() && 7645 PPC::GPRCRegClass.contains(R.first)) { 7646 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo(); 7647 return std::make_pair(TRI->getMatchingSuperReg(R.first, 7648 PPC::sub_32, &PPC::GPRCRegClass), 7649 &PPC::G8RCRegClass); 7650 } 7651 7652 return R; 7653 } 7654 7655 7656 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 7657 /// vector. If it is invalid, don't add anything to Ops. 7658 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 7659 std::string &Constraint, 7660 std::vector<SDValue>&Ops, 7661 SelectionDAG &DAG) const { 7662 SDValue Result(0,0); 7663 7664 // Only support length 1 constraints. 7665 if (Constraint.length() > 1) return; 7666 7667 char Letter = Constraint[0]; 7668 switch (Letter) { 7669 default: break; 7670 case 'I': 7671 case 'J': 7672 case 'K': 7673 case 'L': 7674 case 'M': 7675 case 'N': 7676 case 'O': 7677 case 'P': { 7678 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 7679 if (!CST) return; // Must be an immediate to match. 7680 unsigned Value = CST->getZExtValue(); 7681 switch (Letter) { 7682 default: llvm_unreachable("Unknown constraint letter!"); 7683 case 'I': // "I" is a signed 16-bit constant. 7684 if ((short)Value == (int)Value) 7685 Result = DAG.getTargetConstant(Value, Op.getValueType()); 7686 break; 7687 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 7688 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 7689 if ((short)Value == 0) 7690 Result = DAG.getTargetConstant(Value, Op.getValueType()); 7691 break; 7692 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 7693 if ((Value >> 16) == 0) 7694 Result = DAG.getTargetConstant(Value, Op.getValueType()); 7695 break; 7696 case 'M': // "M" is a constant that is greater than 31. 7697 if (Value > 31) 7698 Result = DAG.getTargetConstant(Value, Op.getValueType()); 7699 break; 7700 case 'N': // "N" is a positive constant that is an exact power of two. 7701 if ((int)Value > 0 && isPowerOf2_32(Value)) 7702 Result = DAG.getTargetConstant(Value, Op.getValueType()); 7703 break; 7704 case 'O': // "O" is the constant zero. 7705 if (Value == 0) 7706 Result = DAG.getTargetConstant(Value, Op.getValueType()); 7707 break; 7708 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 7709 if ((short)-Value == (int)-Value) 7710 Result = DAG.getTargetConstant(Value, Op.getValueType()); 7711 break; 7712 } 7713 break; 7714 } 7715 } 7716 7717 if (Result.getNode()) { 7718 Ops.push_back(Result); 7719 return; 7720 } 7721 7722 // Handle standard constraint letters. 7723 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 7724 } 7725 7726 // isLegalAddressingMode - Return true if the addressing mode represented 7727 // by AM is legal for this target, for a load/store of the specified type. 7728 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM, 7729 Type *Ty) const { 7730 // FIXME: PPC does not allow r+i addressing modes for vectors! 7731 7732 // PPC allows a sign-extended 16-bit immediate field. 7733 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 7734 return false; 7735 7736 // No global is ever allowed as a base. 7737 if (AM.BaseGV) 7738 return false; 7739 7740 // PPC only support r+r, 7741 switch (AM.Scale) { 7742 case 0: // "r+i" or just "i", depending on HasBaseReg. 7743 break; 7744 case 1: 7745 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 7746 return false; 7747 // Otherwise we have r+r or r+i. 7748 break; 7749 case 2: 7750 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 7751 return false; 7752 // Allow 2*r as r+r. 7753 break; 7754 default: 7755 // No other scales are supported. 7756 return false; 7757 } 7758 7759 return true; 7760 } 7761 7762 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 7763 SelectionDAG &DAG) const { 7764 MachineFunction &MF = DAG.getMachineFunction(); 7765 MachineFrameInfo *MFI = MF.getFrameInfo(); 7766 MFI->setReturnAddressIsTaken(true); 7767 7768 SDLoc dl(Op); 7769 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 7770 7771 // Make sure the function does not optimize away the store of the RA to 7772 // the stack. 7773 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7774 FuncInfo->setLRStoreRequired(); 7775 bool isPPC64 = PPCSubTarget.isPPC64(); 7776 bool isDarwinABI = PPCSubTarget.isDarwinABI(); 7777 7778 if (Depth > 0) { 7779 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 7780 SDValue Offset = 7781 7782 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI), 7783 isPPC64? MVT::i64 : MVT::i32); 7784 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 7785 DAG.getNode(ISD::ADD, dl, getPointerTy(), 7786 FrameAddr, Offset), 7787 MachinePointerInfo(), false, false, false, 0); 7788 } 7789 7790 // Just load the return address off the stack. 7791 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 7792 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 7793 RetAddrFI, MachinePointerInfo(), false, false, false, 0); 7794 } 7795 7796 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 7797 SelectionDAG &DAG) const { 7798 SDLoc dl(Op); 7799 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 7800 7801 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 7802 bool isPPC64 = PtrVT == MVT::i64; 7803 7804 MachineFunction &MF = DAG.getMachineFunction(); 7805 MachineFrameInfo *MFI = MF.getFrameInfo(); 7806 MFI->setFrameAddressIsTaken(true); 7807 7808 // Naked functions never have a frame pointer, and so we use r1. For all 7809 // other functions, this decision must be delayed until during PEI. 7810 unsigned FrameReg; 7811 if (MF.getFunction()->getAttributes().hasAttribute( 7812 AttributeSet::FunctionIndex, Attribute::Naked)) 7813 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 7814 else 7815 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 7816 7817 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 7818 PtrVT); 7819 while (Depth--) 7820 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 7821 FrameAddr, MachinePointerInfo(), false, false, 7822 false, 0); 7823 return FrameAddr; 7824 } 7825 7826 bool 7827 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 7828 // The PowerPC target isn't yet aware of offsets. 7829 return false; 7830 } 7831 7832 /// getOptimalMemOpType - Returns the target specific optimal type for load 7833 /// and store operations as a result of memset, memcpy, and memmove 7834 /// lowering. If DstAlign is zero that means it's safe to destination 7835 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 7836 /// means there isn't a need to check it against alignment requirement, 7837 /// probably because the source does not need to be loaded. If 'IsMemset' is 7838 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 7839 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 7840 /// source is constant so it does not need to be loaded. 7841 /// It returns EVT::Other if the type should be determined using generic 7842 /// target-independent logic. 7843 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 7844 unsigned DstAlign, unsigned SrcAlign, 7845 bool IsMemset, bool ZeroMemset, 7846 bool MemcpyStrSrc, 7847 MachineFunction &MF) const { 7848 if (this->PPCSubTarget.isPPC64()) { 7849 return MVT::i64; 7850 } else { 7851 return MVT::i32; 7852 } 7853 } 7854 7855 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, 7856 bool *Fast) const { 7857 if (DisablePPCUnaligned) 7858 return false; 7859 7860 // PowerPC supports unaligned memory access for simple non-vector types. 7861 // Although accessing unaligned addresses is not as efficient as accessing 7862 // aligned addresses, it is generally more efficient than manual expansion, 7863 // and generally only traps for software emulation when crossing page 7864 // boundaries. 7865 7866 if (!VT.isSimple()) 7867 return false; 7868 7869 if (VT.getSimpleVT().isVector()) 7870 return false; 7871 7872 if (VT == MVT::ppcf128) 7873 return false; 7874 7875 if (Fast) 7876 *Fast = true; 7877 7878 return true; 7879 } 7880 7881 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 7882 VT = VT.getScalarType(); 7883 7884 if (!VT.isSimple()) 7885 return false; 7886 7887 switch (VT.getSimpleVT().SimpleTy) { 7888 case MVT::f32: 7889 case MVT::f64: 7890 return true; 7891 default: 7892 break; 7893 } 7894 7895 return false; 7896 } 7897 7898 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 7899 if (DisableILPPref) 7900 return TargetLowering::getSchedulingPreference(N); 7901 7902 return Sched::ILP; 7903 } 7904 7905 // Create a fast isel object. 7906 FastISel * 7907 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 7908 const TargetLibraryInfo *LibInfo) const { 7909 return PPC::createFastISel(FuncInfo, LibInfo); 7910 } 7911