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