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