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