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