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