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