1 //===-- X86ISelLowering.cpp - X86 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 defines the interfaces that X86 uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #define DEBUG_TYPE "x86-isel" 16 #include "X86.h" 17 #include "X86InstrBuilder.h" 18 #include "X86ISelLowering.h" 19 #include "X86TargetMachine.h" 20 #include "X86TargetObjectFile.h" 21 #include "Utils/X86ShuffleDecode.h" 22 #include "llvm/CallingConv.h" 23 #include "llvm/Constants.h" 24 #include "llvm/DerivedTypes.h" 25 #include "llvm/GlobalAlias.h" 26 #include "llvm/GlobalVariable.h" 27 #include "llvm/Function.h" 28 #include "llvm/Instructions.h" 29 #include "llvm/Intrinsics.h" 30 #include "llvm/LLVMContext.h" 31 #include "llvm/CodeGen/IntrinsicLowering.h" 32 #include "llvm/CodeGen/MachineFrameInfo.h" 33 #include "llvm/CodeGen/MachineFunction.h" 34 #include "llvm/CodeGen/MachineInstrBuilder.h" 35 #include "llvm/CodeGen/MachineJumpTableInfo.h" 36 #include "llvm/CodeGen/MachineModuleInfo.h" 37 #include "llvm/CodeGen/MachineRegisterInfo.h" 38 #include "llvm/MC/MCAsmInfo.h" 39 #include "llvm/MC/MCContext.h" 40 #include "llvm/MC/MCExpr.h" 41 #include "llvm/MC/MCSymbol.h" 42 #include "llvm/ADT/BitVector.h" 43 #include "llvm/ADT/SmallSet.h" 44 #include "llvm/ADT/Statistic.h" 45 #include "llvm/ADT/StringExtras.h" 46 #include "llvm/ADT/VectorExtras.h" 47 #include "llvm/Support/CallSite.h" 48 #include "llvm/Support/Debug.h" 49 #include "llvm/Support/Dwarf.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/MathExtras.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include "llvm/Target/TargetOptions.h" 54 using namespace llvm; 55 using namespace dwarf; 56 57 STATISTIC(NumTailCalls, "Number of tail calls"); 58 59 // Forward declarations. 60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 61 SDValue V2); 62 63 static SDValue Insert128BitVector(SDValue Result, 64 SDValue Vec, 65 SDValue Idx, 66 SelectionDAG &DAG, 67 DebugLoc dl); 68 69 static SDValue Extract128BitVector(SDValue Vec, 70 SDValue Idx, 71 SelectionDAG &DAG, 72 DebugLoc dl); 73 74 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This 75 /// sets things up to match to an AVX VEXTRACTF128 instruction or a 76 /// simple subregister reference. Idx is an index in the 128 bits we 77 /// want. It need not be aligned to a 128-bit bounday. That makes 78 /// lowering EXTRACT_VECTOR_ELT operations easier. 79 static SDValue Extract128BitVector(SDValue Vec, 80 SDValue Idx, 81 SelectionDAG &DAG, 82 DebugLoc dl) { 83 EVT VT = Vec.getValueType(); 84 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!"); 85 EVT ElVT = VT.getVectorElementType(); 86 int Factor = VT.getSizeInBits()/128; 87 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, 88 VT.getVectorNumElements()/Factor); 89 90 // Extract from UNDEF is UNDEF. 91 if (Vec.getOpcode() == ISD::UNDEF) 92 return DAG.getNode(ISD::UNDEF, dl, ResultVT); 93 94 if (isa<ConstantSDNode>(Idx)) { 95 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 96 97 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR 98 // we can match to VEXTRACTF128. 99 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 100 101 // This is the index of the first element of the 128-bit chunk 102 // we want. 103 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 104 * ElemsPerChunk); 105 106 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 107 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, 108 VecIdx); 109 110 return Result; 111 } 112 113 return SDValue(); 114 } 115 116 /// Generate a DAG to put 128-bits into a vector > 128 bits. This 117 /// sets things up to match to an AVX VINSERTF128 instruction or a 118 /// simple superregister reference. Idx is an index in the 128 bits 119 /// we want. It need not be aligned to a 128-bit bounday. That makes 120 /// lowering INSERT_VECTOR_ELT operations easier. 121 static SDValue Insert128BitVector(SDValue Result, 122 SDValue Vec, 123 SDValue Idx, 124 SelectionDAG &DAG, 125 DebugLoc dl) { 126 if (isa<ConstantSDNode>(Idx)) { 127 EVT VT = Vec.getValueType(); 128 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!"); 129 130 EVT ElVT = VT.getVectorElementType(); 131 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 132 EVT ResultVT = Result.getValueType(); 133 134 // Insert the relevant 128 bits. 135 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits(); 136 137 // This is the index of the first element of the 128-bit chunk 138 // we want. 139 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128) 140 * ElemsPerChunk); 141 142 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 143 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, 144 VecIdx); 145 return Result; 146 } 147 148 return SDValue(); 149 } 150 151 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) { 152 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); 153 bool is64Bit = Subtarget->is64Bit(); 154 155 if (Subtarget->isTargetEnvMacho()) { 156 if (is64Bit) 157 return new X8664_MachoTargetObjectFile(); 158 return new TargetLoweringObjectFileMachO(); 159 } 160 161 if (Subtarget->isTargetELF()) 162 return new TargetLoweringObjectFileELF(); 163 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 164 return new TargetLoweringObjectFileCOFF(); 165 llvm_unreachable("unknown subtarget type"); 166 } 167 168 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM) 169 : TargetLowering(TM, createTLOF(TM)) { 170 Subtarget = &TM.getSubtarget<X86Subtarget>(); 171 X86ScalarSSEf64 = Subtarget->hasXMMInt(); 172 X86ScalarSSEf32 = Subtarget->hasXMM(); 173 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP; 174 175 RegInfo = TM.getRegisterInfo(); 176 TD = getTargetData(); 177 178 // Set up the TargetLowering object. 179 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }; 180 181 // X86 is weird, it always uses i8 for shift amounts and setcc results. 182 setBooleanContents(ZeroOrOneBooleanContent); 183 // X86-SSE is even stranger. It uses -1 or 0 for vector masks. 184 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 185 186 // For 64-bit since we have so many registers use the ILP scheduler, for 187 // 32-bit code use the register pressure specific scheduling. 188 if (Subtarget->is64Bit()) 189 setSchedulingPreference(Sched::ILP); 190 else 191 setSchedulingPreference(Sched::RegPressure); 192 setStackPointerRegisterToSaveRestore(X86StackPtr); 193 194 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) { 195 // Setup Windows compiler runtime calls. 196 setLibcallName(RTLIB::SDIV_I64, "_alldiv"); 197 setLibcallName(RTLIB::UDIV_I64, "_aulldiv"); 198 setLibcallName(RTLIB::SREM_I64, "_allrem"); 199 setLibcallName(RTLIB::UREM_I64, "_aullrem"); 200 setLibcallName(RTLIB::MUL_I64, "_allmul"); 201 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2"); 202 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2"); 203 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall); 204 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall); 205 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall); 206 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall); 207 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall); 208 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C); 209 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C); 210 } 211 212 if (Subtarget->isTargetDarwin()) { 213 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp. 214 setUseUnderscoreSetJmp(false); 215 setUseUnderscoreLongJmp(false); 216 } else if (Subtarget->isTargetMingw()) { 217 // MS runtime is weird: it exports _setjmp, but longjmp! 218 setUseUnderscoreSetJmp(true); 219 setUseUnderscoreLongJmp(false); 220 } else { 221 setUseUnderscoreSetJmp(true); 222 setUseUnderscoreLongJmp(true); 223 } 224 225 // Set up the register classes. 226 addRegisterClass(MVT::i8, X86::GR8RegisterClass); 227 addRegisterClass(MVT::i16, X86::GR16RegisterClass); 228 addRegisterClass(MVT::i32, X86::GR32RegisterClass); 229 if (Subtarget->is64Bit()) 230 addRegisterClass(MVT::i64, X86::GR64RegisterClass); 231 232 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 233 234 // We don't accept any truncstore of integer registers. 235 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 236 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 237 setTruncStoreAction(MVT::i64, MVT::i8 , Expand); 238 setTruncStoreAction(MVT::i32, MVT::i16, Expand); 239 setTruncStoreAction(MVT::i32, MVT::i8 , Expand); 240 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 241 242 // SETOEQ and SETUNE require checking two conditions. 243 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand); 244 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand); 245 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand); 246 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand); 247 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand); 248 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand); 249 250 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this 251 // operation. 252 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote); 253 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote); 254 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote); 255 256 if (Subtarget->is64Bit()) { 257 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote); 258 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand); 259 } else if (!UseSoftFloat) { 260 // We have an algorithm for SSE2->double, and we turn this into a 261 // 64-bit FILD followed by conditional FADD for other targets. 262 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 263 // We have an algorithm for SSE2, and we turn this into a 64-bit 264 // FILD for other targets. 265 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom); 266 } 267 268 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have 269 // this operation. 270 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote); 271 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote); 272 273 if (!UseSoftFloat) { 274 // SSE has no i16 to fp conversion, only i32 275 if (X86ScalarSSEf32) { 276 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 277 // f32 and f64 cases are Legal, f80 case is not 278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 279 } else { 280 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom); 281 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 282 } 283 } else { 284 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 285 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote); 286 } 287 288 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64 289 // are Legal, f80 is custom lowered. 290 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom); 291 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom); 292 293 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have 294 // this operation. 295 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote); 296 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote); 297 298 if (X86ScalarSSEf32) { 299 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote); 300 // f32 and f64 cases are Legal, f80 case is not 301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 302 } else { 303 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom); 304 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 305 } 306 307 // Handle FP_TO_UINT by promoting the destination to a larger signed 308 // conversion. 309 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote); 310 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote); 311 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote); 312 313 if (Subtarget->is64Bit()) { 314 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand); 315 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote); 316 } else if (!UseSoftFloat) { 317 // Since AVX is a superset of SSE3, only check for SSE here. 318 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3()) 319 // Expand FP_TO_UINT into a select. 320 // FIXME: We would like to use a Custom expander here eventually to do 321 // the optimal thing for SSE vs. the default expansion in the legalizer. 322 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand); 323 else 324 // With SSE3 we can use fisttpll to convert to a signed i64; without 325 // SSE, we're stuck with a fistpll. 326 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom); 327 } 328 329 // TODO: when we have SSE, these could be more efficient, by using movd/movq. 330 if (!X86ScalarSSEf64) { 331 setOperationAction(ISD::BITCAST , MVT::f32 , Expand); 332 setOperationAction(ISD::BITCAST , MVT::i32 , Expand); 333 if (Subtarget->is64Bit()) { 334 setOperationAction(ISD::BITCAST , MVT::f64 , Expand); 335 // Without SSE, i64->f64 goes through memory. 336 setOperationAction(ISD::BITCAST , MVT::i64 , Expand); 337 } 338 } 339 340 // Scalar integer divide and remainder are lowered to use operations that 341 // produce two results, to match the available instructions. This exposes 342 // the two-result form to trivial CSE, which is able to combine x/y and x%y 343 // into a single instruction. 344 // 345 // Scalar integer multiply-high is also lowered to use two-result 346 // operations, to match the available instructions. However, plain multiply 347 // (low) operations are left as Legal, as there are single-result 348 // instructions for this in x86. Using the two-result multiply instructions 349 // when both high and low results are needed must be arranged by dagcombine. 350 for (unsigned i = 0, e = 4; i != e; ++i) { 351 MVT VT = IntVTs[i]; 352 setOperationAction(ISD::MULHS, VT, Expand); 353 setOperationAction(ISD::MULHU, VT, Expand); 354 setOperationAction(ISD::SDIV, VT, Expand); 355 setOperationAction(ISD::UDIV, VT, Expand); 356 setOperationAction(ISD::SREM, VT, Expand); 357 setOperationAction(ISD::UREM, VT, Expand); 358 359 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences. 360 setOperationAction(ISD::ADDC, VT, Custom); 361 setOperationAction(ISD::ADDE, VT, Custom); 362 setOperationAction(ISD::SUBC, VT, Custom); 363 setOperationAction(ISD::SUBE, VT, Custom); 364 } 365 366 setOperationAction(ISD::BR_JT , MVT::Other, Expand); 367 setOperationAction(ISD::BRCOND , MVT::Other, Custom); 368 setOperationAction(ISD::BR_CC , MVT::Other, Expand); 369 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand); 370 if (Subtarget->is64Bit()) 371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal); 373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal); 374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand); 375 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand); 376 setOperationAction(ISD::FREM , MVT::f32 , Expand); 377 setOperationAction(ISD::FREM , MVT::f64 , Expand); 378 setOperationAction(ISD::FREM , MVT::f80 , Expand); 379 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom); 380 381 if (Subtarget->hasBMI()) { 382 setOperationAction(ISD::CTTZ , MVT::i8 , Promote); 383 } else { 384 setOperationAction(ISD::CTTZ , MVT::i8 , Custom); 385 setOperationAction(ISD::CTTZ , MVT::i16 , Custom); 386 setOperationAction(ISD::CTTZ , MVT::i32 , Custom); 387 if (Subtarget->is64Bit()) 388 setOperationAction(ISD::CTTZ , MVT::i64 , Custom); 389 } 390 391 if (Subtarget->hasLZCNT()) { 392 setOperationAction(ISD::CTLZ , MVT::i8 , Promote); 393 } else { 394 setOperationAction(ISD::CTLZ , MVT::i8 , Custom); 395 setOperationAction(ISD::CTLZ , MVT::i16 , Custom); 396 setOperationAction(ISD::CTLZ , MVT::i32 , Custom); 397 if (Subtarget->is64Bit()) 398 setOperationAction(ISD::CTLZ , MVT::i64 , Custom); 399 } 400 401 if (Subtarget->hasPOPCNT()) { 402 setOperationAction(ISD::CTPOP , MVT::i8 , Promote); 403 } else { 404 setOperationAction(ISD::CTPOP , MVT::i8 , Expand); 405 setOperationAction(ISD::CTPOP , MVT::i16 , Expand); 406 setOperationAction(ISD::CTPOP , MVT::i32 , Expand); 407 if (Subtarget->is64Bit()) 408 setOperationAction(ISD::CTPOP , MVT::i64 , Expand); 409 } 410 411 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom); 412 setOperationAction(ISD::BSWAP , MVT::i16 , Expand); 413 414 // These should be promoted to a larger select which is supported. 415 setOperationAction(ISD::SELECT , MVT::i1 , Promote); 416 // X86 wants to expand cmov itself. 417 setOperationAction(ISD::SELECT , MVT::i8 , Custom); 418 setOperationAction(ISD::SELECT , MVT::i16 , Custom); 419 setOperationAction(ISD::SELECT , MVT::i32 , Custom); 420 setOperationAction(ISD::SELECT , MVT::f32 , Custom); 421 setOperationAction(ISD::SELECT , MVT::f64 , Custom); 422 setOperationAction(ISD::SELECT , MVT::f80 , Custom); 423 setOperationAction(ISD::SETCC , MVT::i8 , Custom); 424 setOperationAction(ISD::SETCC , MVT::i16 , Custom); 425 setOperationAction(ISD::SETCC , MVT::i32 , Custom); 426 setOperationAction(ISD::SETCC , MVT::f32 , Custom); 427 setOperationAction(ISD::SETCC , MVT::f64 , Custom); 428 setOperationAction(ISD::SETCC , MVT::f80 , Custom); 429 if (Subtarget->is64Bit()) { 430 setOperationAction(ISD::SELECT , MVT::i64 , Custom); 431 setOperationAction(ISD::SETCC , MVT::i64 , Custom); 432 } 433 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom); 434 435 // Darwin ABI issue. 436 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom); 437 setOperationAction(ISD::JumpTable , MVT::i32 , Custom); 438 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom); 439 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom); 440 if (Subtarget->is64Bit()) 441 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 442 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom); 443 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom); 444 if (Subtarget->is64Bit()) { 445 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom); 446 setOperationAction(ISD::JumpTable , MVT::i64 , Custom); 447 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom); 448 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom); 449 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom); 450 } 451 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86) 452 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom); 453 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom); 454 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom); 455 if (Subtarget->is64Bit()) { 456 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom); 457 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom); 458 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom); 459 } 460 461 if (Subtarget->hasXMM()) 462 setOperationAction(ISD::PREFETCH , MVT::Other, Legal); 463 464 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom); 465 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom); 466 467 // On X86 and X86-64, atomic operations are lowered to locked instructions. 468 // Locked instructions, in turn, have implicit fence semantics (all memory 469 // operations are flushed before issuing the locked instruction, and they 470 // are not buffered), so we can fold away the common pattern of 471 // fence-atomic-fence. 472 setShouldFoldAtomicFences(true); 473 474 // Expand certain atomics 475 for (unsigned i = 0, e = 4; i != e; ++i) { 476 MVT VT = IntVTs[i]; 477 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom); 478 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 479 setOperationAction(ISD::ATOMIC_STORE, VT, Custom); 480 } 481 482 if (!Subtarget->is64Bit()) { 483 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom); 484 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom); 485 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 486 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 487 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom); 488 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom); 489 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom); 490 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom); 491 } 492 493 if (Subtarget->hasCmpxchg16b()) { 494 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 495 } 496 497 // FIXME - use subtarget debug flags 498 if (!Subtarget->isTargetDarwin() && 499 !Subtarget->isTargetELF() && 500 !Subtarget->isTargetCygMing()) { 501 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); 502 } 503 504 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand); 505 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand); 506 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand); 507 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand); 508 if (Subtarget->is64Bit()) { 509 setExceptionPointerRegister(X86::RAX); 510 setExceptionSelectorRegister(X86::RDX); 511 } else { 512 setExceptionPointerRegister(X86::EAX); 513 setExceptionSelectorRegister(X86::EDX); 514 } 515 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom); 516 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom); 517 518 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 519 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 520 521 setOperationAction(ISD::TRAP, MVT::Other, Legal); 522 523 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 524 setOperationAction(ISD::VASTART , MVT::Other, Custom); 525 setOperationAction(ISD::VAEND , MVT::Other, Expand); 526 if (Subtarget->is64Bit()) { 527 setOperationAction(ISD::VAARG , MVT::Other, Custom); 528 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 529 } else { 530 setOperationAction(ISD::VAARG , MVT::Other, Expand); 531 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 532 } 533 534 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 535 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 536 537 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 538 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 539 MVT::i64 : MVT::i32, Custom); 540 else if (EnableSegmentedStacks) 541 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 542 MVT::i64 : MVT::i32, Custom); 543 else 544 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 545 MVT::i64 : MVT::i32, Expand); 546 547 if (!UseSoftFloat && X86ScalarSSEf64) { 548 // f32 and f64 use SSE. 549 // Set up the FP register classes. 550 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 551 addRegisterClass(MVT::f64, X86::FR64RegisterClass); 552 553 // Use ANDPD to simulate FABS. 554 setOperationAction(ISD::FABS , MVT::f64, Custom); 555 setOperationAction(ISD::FABS , MVT::f32, Custom); 556 557 // Use XORP to simulate FNEG. 558 setOperationAction(ISD::FNEG , MVT::f64, Custom); 559 setOperationAction(ISD::FNEG , MVT::f32, Custom); 560 561 // Use ANDPD and ORPD to simulate FCOPYSIGN. 562 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 563 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 564 565 // Lower this to FGETSIGNx86 plus an AND. 566 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom); 567 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom); 568 569 // We don't support sin/cos/fmod 570 setOperationAction(ISD::FSIN , MVT::f64, Expand); 571 setOperationAction(ISD::FCOS , MVT::f64, Expand); 572 setOperationAction(ISD::FSIN , MVT::f32, Expand); 573 setOperationAction(ISD::FCOS , MVT::f32, Expand); 574 575 // Expand FP immediates into loads from the stack, except for the special 576 // cases we handle. 577 addLegalFPImmediate(APFloat(+0.0)); // xorpd 578 addLegalFPImmediate(APFloat(+0.0f)); // xorps 579 } else if (!UseSoftFloat && X86ScalarSSEf32) { 580 // Use SSE for f32, x87 for f64. 581 // Set up the FP register classes. 582 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 583 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 584 585 // Use ANDPS to simulate FABS. 586 setOperationAction(ISD::FABS , MVT::f32, Custom); 587 588 // Use XORP to simulate FNEG. 589 setOperationAction(ISD::FNEG , MVT::f32, Custom); 590 591 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 592 593 // Use ANDPS and ORPS to simulate FCOPYSIGN. 594 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 595 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 596 597 // We don't support sin/cos/fmod 598 setOperationAction(ISD::FSIN , MVT::f32, Expand); 599 setOperationAction(ISD::FCOS , MVT::f32, Expand); 600 601 // Special cases we handle for FP constants. 602 addLegalFPImmediate(APFloat(+0.0f)); // xorps 603 addLegalFPImmediate(APFloat(+0.0)); // FLD0 604 addLegalFPImmediate(APFloat(+1.0)); // FLD1 605 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 606 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 607 608 if (!UnsafeFPMath) { 609 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 610 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 611 } 612 } else if (!UseSoftFloat) { 613 // f32 and f64 in x87. 614 // Set up the FP register classes. 615 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 616 addRegisterClass(MVT::f32, X86::RFP32RegisterClass); 617 618 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 619 setOperationAction(ISD::UNDEF, MVT::f32, Expand); 620 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 621 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 622 623 if (!UnsafeFPMath) { 624 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 625 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 626 } 627 addLegalFPImmediate(APFloat(+0.0)); // FLD0 628 addLegalFPImmediate(APFloat(+1.0)); // FLD1 629 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 630 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 631 addLegalFPImmediate(APFloat(+0.0f)); // FLD0 632 addLegalFPImmediate(APFloat(+1.0f)); // FLD1 633 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS 634 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS 635 } 636 637 // We don't support FMA. 638 setOperationAction(ISD::FMA, MVT::f64, Expand); 639 setOperationAction(ISD::FMA, MVT::f32, Expand); 640 641 // Long double always uses X87. 642 if (!UseSoftFloat) { 643 addRegisterClass(MVT::f80, X86::RFP80RegisterClass); 644 setOperationAction(ISD::UNDEF, MVT::f80, Expand); 645 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand); 646 { 647 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended); 648 addLegalFPImmediate(TmpFlt); // FLD0 649 TmpFlt.changeSign(); 650 addLegalFPImmediate(TmpFlt); // FLD0/FCHS 651 652 bool ignored; 653 APFloat TmpFlt2(+1.0); 654 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, 655 &ignored); 656 addLegalFPImmediate(TmpFlt2); // FLD1 657 TmpFlt2.changeSign(); 658 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS 659 } 660 661 if (!UnsafeFPMath) { 662 setOperationAction(ISD::FSIN , MVT::f80 , Expand); 663 setOperationAction(ISD::FCOS , MVT::f80 , Expand); 664 } 665 666 setOperationAction(ISD::FMA, MVT::f80, Expand); 667 } 668 669 // Always use a library call for pow. 670 setOperationAction(ISD::FPOW , MVT::f32 , Expand); 671 setOperationAction(ISD::FPOW , MVT::f64 , Expand); 672 setOperationAction(ISD::FPOW , MVT::f80 , Expand); 673 674 setOperationAction(ISD::FLOG, MVT::f80, Expand); 675 setOperationAction(ISD::FLOG2, MVT::f80, Expand); 676 setOperationAction(ISD::FLOG10, MVT::f80, Expand); 677 setOperationAction(ISD::FEXP, MVT::f80, Expand); 678 setOperationAction(ISD::FEXP2, MVT::f80, Expand); 679 680 // First set operation action for all vector types to either promote 681 // (for widening) or expand (for scalarization). Then we will selectively 682 // turn on ones that can be effectively codegen'd. 683 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 684 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) { 685 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand); 686 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand); 687 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand); 688 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand); 689 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand); 690 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand); 691 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand); 692 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand); 693 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand); 694 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand); 695 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand); 696 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand); 697 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand); 698 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand); 699 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand); 700 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand); 701 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 702 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 703 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand); 704 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand); 705 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand); 706 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand); 707 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand); 708 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand); 709 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand); 710 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 711 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 712 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand); 713 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand); 714 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand); 715 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand); 716 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand); 717 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand); 718 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand); 719 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand); 720 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand); 721 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand); 722 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand); 723 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand); 724 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand); 725 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand); 726 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand); 727 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand); 728 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand); 729 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand); 730 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand); 731 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand); 732 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 733 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 734 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand); 735 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand); 736 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand); 737 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand); 738 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand); 739 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand); 740 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 741 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 742 setTruncStoreAction((MVT::SimpleValueType)VT, 743 (MVT::SimpleValueType)InnerVT, Expand); 744 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand); 745 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand); 746 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand); 747 } 748 749 // FIXME: In order to prevent SSE instructions being expanded to MMX ones 750 // with -msoft-float, disable use of MMX as well. 751 if (!UseSoftFloat && Subtarget->hasMMX()) { 752 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass); 753 // No operations on x86mmx supported, everything uses intrinsics. 754 } 755 756 // MMX-sized vectors (other than x86mmx) are expected to be expanded 757 // into smaller operations. 758 setOperationAction(ISD::MULHS, MVT::v8i8, Expand); 759 setOperationAction(ISD::MULHS, MVT::v4i16, Expand); 760 setOperationAction(ISD::MULHS, MVT::v2i32, Expand); 761 setOperationAction(ISD::MULHS, MVT::v1i64, Expand); 762 setOperationAction(ISD::AND, MVT::v8i8, Expand); 763 setOperationAction(ISD::AND, MVT::v4i16, Expand); 764 setOperationAction(ISD::AND, MVT::v2i32, Expand); 765 setOperationAction(ISD::AND, MVT::v1i64, Expand); 766 setOperationAction(ISD::OR, MVT::v8i8, Expand); 767 setOperationAction(ISD::OR, MVT::v4i16, Expand); 768 setOperationAction(ISD::OR, MVT::v2i32, Expand); 769 setOperationAction(ISD::OR, MVT::v1i64, Expand); 770 setOperationAction(ISD::XOR, MVT::v8i8, Expand); 771 setOperationAction(ISD::XOR, MVT::v4i16, Expand); 772 setOperationAction(ISD::XOR, MVT::v2i32, Expand); 773 setOperationAction(ISD::XOR, MVT::v1i64, Expand); 774 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand); 775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand); 776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand); 777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand); 778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand); 779 setOperationAction(ISD::SELECT, MVT::v8i8, Expand); 780 setOperationAction(ISD::SELECT, MVT::v4i16, Expand); 781 setOperationAction(ISD::SELECT, MVT::v2i32, Expand); 782 setOperationAction(ISD::SELECT, MVT::v1i64, Expand); 783 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand); 784 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand); 785 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand); 786 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand); 787 788 if (!UseSoftFloat && Subtarget->hasXMM()) { 789 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass); 790 791 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 792 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 793 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 794 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 795 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 796 setOperationAction(ISD::FNEG, MVT::v4f32, Custom); 797 setOperationAction(ISD::LOAD, MVT::v4f32, Legal); 798 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 799 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom); 800 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 801 setOperationAction(ISD::SELECT, MVT::v4f32, Custom); 802 setOperationAction(ISD::SETCC, MVT::v4f32, Custom); 803 } 804 805 if (!UseSoftFloat && Subtarget->hasXMMInt()) { 806 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass); 807 808 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM 809 // registers cannot be used even for integer operations. 810 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass); 811 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass); 812 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass); 813 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass); 814 815 setOperationAction(ISD::ADD, MVT::v16i8, Legal); 816 setOperationAction(ISD::ADD, MVT::v8i16, Legal); 817 setOperationAction(ISD::ADD, MVT::v4i32, Legal); 818 setOperationAction(ISD::ADD, MVT::v2i64, Legal); 819 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 820 setOperationAction(ISD::SUB, MVT::v16i8, Legal); 821 setOperationAction(ISD::SUB, MVT::v8i16, Legal); 822 setOperationAction(ISD::SUB, MVT::v4i32, Legal); 823 setOperationAction(ISD::SUB, MVT::v2i64, Legal); 824 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 825 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 826 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 827 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 828 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 829 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 830 setOperationAction(ISD::FNEG, MVT::v2f64, Custom); 831 832 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 833 setOperationAction(ISD::SETCC, MVT::v16i8, Custom); 834 setOperationAction(ISD::SETCC, MVT::v8i16, Custom); 835 setOperationAction(ISD::SETCC, MVT::v4i32, Custom); 836 837 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom); 838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom); 839 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 842 843 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom); 844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom); 845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom); 846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom); 847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom); 848 849 // Custom lower build_vector, vector_shuffle, and extract_vector_elt. 850 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) { 851 EVT VT = (MVT::SimpleValueType)i; 852 // Do not attempt to custom lower non-power-of-2 vectors 853 if (!isPowerOf2_32(VT.getVectorNumElements())) 854 continue; 855 // Do not attempt to custom lower non-128-bit vectors 856 if (!VT.is128BitVector()) 857 continue; 858 setOperationAction(ISD::BUILD_VECTOR, 859 VT.getSimpleVT().SimpleTy, Custom); 860 setOperationAction(ISD::VECTOR_SHUFFLE, 861 VT.getSimpleVT().SimpleTy, Custom); 862 setOperationAction(ISD::EXTRACT_VECTOR_ELT, 863 VT.getSimpleVT().SimpleTy, Custom); 864 } 865 866 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 868 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 871 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 872 873 if (Subtarget->is64Bit()) { 874 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 875 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 876 } 877 878 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 879 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) { 880 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 881 EVT VT = SVT; 882 883 // Do not attempt to promote non-128-bit vectors 884 if (!VT.is128BitVector()) 885 continue; 886 887 setOperationAction(ISD::AND, SVT, Promote); 888 AddPromotedToType (ISD::AND, SVT, MVT::v2i64); 889 setOperationAction(ISD::OR, SVT, Promote); 890 AddPromotedToType (ISD::OR, SVT, MVT::v2i64); 891 setOperationAction(ISD::XOR, SVT, Promote); 892 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64); 893 setOperationAction(ISD::LOAD, SVT, Promote); 894 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64); 895 setOperationAction(ISD::SELECT, SVT, Promote); 896 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64); 897 } 898 899 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 900 901 // Custom lower v2i64 and v2f64 selects. 902 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 903 setOperationAction(ISD::LOAD, MVT::v2i64, Legal); 904 setOperationAction(ISD::SELECT, MVT::v2f64, Custom); 905 setOperationAction(ISD::SELECT, MVT::v2i64, Custom); 906 907 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 908 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 909 } 910 911 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) { 912 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 913 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 914 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 915 setOperationAction(ISD::FRINT, MVT::f32, Legal); 916 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 917 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 918 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 919 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 920 setOperationAction(ISD::FRINT, MVT::f64, Legal); 921 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 922 923 // FIXME: Do we need to handle scalar-to-vector here? 924 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 925 926 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 927 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal); 928 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 929 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 930 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 931 932 // i8 and i16 vectors are custom , because the source register and source 933 // source memory operand types are not the same width. f32 vectors are 934 // custom since the immediate controlling the insert encodes additional 935 // information. 936 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 938 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 939 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 940 941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom); 942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom); 943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom); 944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 945 946 // FIXME: these should be Legal but thats only for the case where 947 // the index is constant. For now custom expand to deal with that 948 if (Subtarget->is64Bit()) { 949 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 950 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 951 } 952 } 953 954 if (Subtarget->hasXMMInt()) { 955 setOperationAction(ISD::SRL, MVT::v8i16, Custom); 956 setOperationAction(ISD::SRL, MVT::v16i8, Custom); 957 958 setOperationAction(ISD::SHL, MVT::v8i16, Custom); 959 setOperationAction(ISD::SHL, MVT::v16i8, Custom); 960 961 setOperationAction(ISD::SRA, MVT::v8i16, Custom); 962 setOperationAction(ISD::SRA, MVT::v16i8, Custom); 963 964 if (Subtarget->hasAVX2()) { 965 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 966 setOperationAction(ISD::SRL, MVT::v4i32, Legal); 967 968 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 969 setOperationAction(ISD::SHL, MVT::v4i32, Legal); 970 971 setOperationAction(ISD::SRA, MVT::v4i32, Legal); 972 } else { 973 setOperationAction(ISD::SRL, MVT::v2i64, Custom); 974 setOperationAction(ISD::SRL, MVT::v4i32, Custom); 975 976 setOperationAction(ISD::SHL, MVT::v2i64, Custom); 977 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 978 979 setOperationAction(ISD::SRA, MVT::v4i32, Custom); 980 } 981 } 982 983 if (Subtarget->hasSSE42() || Subtarget->hasAVX()) 984 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 985 986 if (!UseSoftFloat && Subtarget->hasAVX()) { 987 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass); 988 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass); 989 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass); 990 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass); 991 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass); 992 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass); 993 994 setOperationAction(ISD::LOAD, MVT::v8f32, Legal); 995 setOperationAction(ISD::LOAD, MVT::v4f64, Legal); 996 setOperationAction(ISD::LOAD, MVT::v4i64, Legal); 997 998 setOperationAction(ISD::FADD, MVT::v8f32, Legal); 999 setOperationAction(ISD::FSUB, MVT::v8f32, Legal); 1000 setOperationAction(ISD::FMUL, MVT::v8f32, Legal); 1001 setOperationAction(ISD::FDIV, MVT::v8f32, Legal); 1002 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal); 1003 setOperationAction(ISD::FNEG, MVT::v8f32, Custom); 1004 1005 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1006 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1007 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1008 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1009 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1010 setOperationAction(ISD::FNEG, MVT::v4f64, Custom); 1011 1012 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal); 1013 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal); 1014 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal); 1015 1016 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom); 1017 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom); 1018 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom); 1019 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom); 1020 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom); 1021 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom); 1022 1023 setOperationAction(ISD::SRL, MVT::v16i16, Custom); 1024 setOperationAction(ISD::SRL, MVT::v32i8, Custom); 1025 1026 setOperationAction(ISD::SHL, MVT::v16i16, Custom); 1027 setOperationAction(ISD::SHL, MVT::v32i8, Custom); 1028 1029 setOperationAction(ISD::SRA, MVT::v16i16, Custom); 1030 setOperationAction(ISD::SRA, MVT::v32i8, Custom); 1031 1032 setOperationAction(ISD::SETCC, MVT::v32i8, Custom); 1033 setOperationAction(ISD::SETCC, MVT::v16i16, Custom); 1034 setOperationAction(ISD::SETCC, MVT::v8i32, Custom); 1035 setOperationAction(ISD::SETCC, MVT::v4i64, Custom); 1036 1037 setOperationAction(ISD::SELECT, MVT::v4f64, Custom); 1038 setOperationAction(ISD::SELECT, MVT::v4i64, Custom); 1039 setOperationAction(ISD::SELECT, MVT::v8f32, Custom); 1040 1041 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1042 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal); 1043 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal); 1044 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal); 1045 1046 if (Subtarget->hasAVX2()) { 1047 setOperationAction(ISD::ADD, MVT::v4i64, Legal); 1048 setOperationAction(ISD::ADD, MVT::v8i32, Legal); 1049 setOperationAction(ISD::ADD, MVT::v16i16, Legal); 1050 setOperationAction(ISD::ADD, MVT::v32i8, Legal); 1051 1052 setOperationAction(ISD::SUB, MVT::v4i64, Legal); 1053 setOperationAction(ISD::SUB, MVT::v8i32, Legal); 1054 setOperationAction(ISD::SUB, MVT::v16i16, Legal); 1055 setOperationAction(ISD::SUB, MVT::v32i8, Legal); 1056 1057 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1058 setOperationAction(ISD::MUL, MVT::v8i32, Legal); 1059 setOperationAction(ISD::MUL, MVT::v16i16, Legal); 1060 // Don't lower v32i8 because there is no 128-bit byte mul 1061 1062 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal); 1063 1064 setOperationAction(ISD::SRL, MVT::v4i64, Legal); 1065 setOperationAction(ISD::SRL, MVT::v8i32, Legal); 1066 1067 setOperationAction(ISD::SHL, MVT::v4i64, Legal); 1068 setOperationAction(ISD::SHL, MVT::v8i32, Legal); 1069 1070 setOperationAction(ISD::SRA, MVT::v8i32, Legal); 1071 } else { 1072 setOperationAction(ISD::ADD, MVT::v4i64, Custom); 1073 setOperationAction(ISD::ADD, MVT::v8i32, Custom); 1074 setOperationAction(ISD::ADD, MVT::v16i16, Custom); 1075 setOperationAction(ISD::ADD, MVT::v32i8, Custom); 1076 1077 setOperationAction(ISD::SUB, MVT::v4i64, Custom); 1078 setOperationAction(ISD::SUB, MVT::v8i32, Custom); 1079 setOperationAction(ISD::SUB, MVT::v16i16, Custom); 1080 setOperationAction(ISD::SUB, MVT::v32i8, Custom); 1081 1082 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1083 setOperationAction(ISD::MUL, MVT::v8i32, Custom); 1084 setOperationAction(ISD::MUL, MVT::v16i16, Custom); 1085 // Don't lower v32i8 because there is no 128-bit byte mul 1086 1087 setOperationAction(ISD::SRL, MVT::v4i64, Custom); 1088 setOperationAction(ISD::SRL, MVT::v8i32, Custom); 1089 1090 setOperationAction(ISD::SHL, MVT::v4i64, Custom); 1091 setOperationAction(ISD::SHL, MVT::v8i32, Custom); 1092 1093 setOperationAction(ISD::SRA, MVT::v8i32, Custom); 1094 } 1095 1096 // Custom lower several nodes for 256-bit types. 1097 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1098 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) { 1099 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 1100 EVT VT = SVT; 1101 1102 // Extract subvector is special because the value type 1103 // (result) is 128-bit but the source is 256-bit wide. 1104 if (VT.is128BitVector()) 1105 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom); 1106 1107 // Do not attempt to custom lower other non-256-bit vectors 1108 if (!VT.is256BitVector()) 1109 continue; 1110 1111 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom); 1112 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom); 1113 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom); 1114 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom); 1115 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom); 1116 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom); 1117 } 1118 1119 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64. 1120 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) { 1121 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 1122 EVT VT = SVT; 1123 1124 // Do not attempt to promote non-256-bit vectors 1125 if (!VT.is256BitVector()) 1126 continue; 1127 1128 setOperationAction(ISD::AND, SVT, Promote); 1129 AddPromotedToType (ISD::AND, SVT, MVT::v4i64); 1130 setOperationAction(ISD::OR, SVT, Promote); 1131 AddPromotedToType (ISD::OR, SVT, MVT::v4i64); 1132 setOperationAction(ISD::XOR, SVT, Promote); 1133 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64); 1134 setOperationAction(ISD::LOAD, SVT, Promote); 1135 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64); 1136 setOperationAction(ISD::SELECT, SVT, Promote); 1137 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64); 1138 } 1139 } 1140 1141 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion 1142 // of this type with custom code. 1143 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1144 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) { 1145 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom); 1146 } 1147 1148 // We want to custom lower some of our intrinsics. 1149 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1150 1151 1152 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't 1153 // handle type legalization for these operations here. 1154 // 1155 // FIXME: We really should do custom legalization for addition and 1156 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better 1157 // than generic legalization for 64-bit multiplication-with-overflow, though. 1158 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) { 1159 // Add/Sub/Mul with overflow operations are custom lowered. 1160 MVT VT = IntVTs[i]; 1161 setOperationAction(ISD::SADDO, VT, Custom); 1162 setOperationAction(ISD::UADDO, VT, Custom); 1163 setOperationAction(ISD::SSUBO, VT, Custom); 1164 setOperationAction(ISD::USUBO, VT, Custom); 1165 setOperationAction(ISD::SMULO, VT, Custom); 1166 setOperationAction(ISD::UMULO, VT, Custom); 1167 } 1168 1169 // There are no 8-bit 3-address imul/mul instructions 1170 setOperationAction(ISD::SMULO, MVT::i8, Expand); 1171 setOperationAction(ISD::UMULO, MVT::i8, Expand); 1172 1173 if (!Subtarget->is64Bit()) { 1174 // These libcalls are not available in 32-bit. 1175 setLibcallName(RTLIB::SHL_I128, 0); 1176 setLibcallName(RTLIB::SRL_I128, 0); 1177 setLibcallName(RTLIB::SRA_I128, 0); 1178 } 1179 1180 // We have target-specific dag combine patterns for the following nodes: 1181 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1182 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 1183 setTargetDAGCombine(ISD::BUILD_VECTOR); 1184 setTargetDAGCombine(ISD::VSELECT); 1185 setTargetDAGCombine(ISD::SELECT); 1186 setTargetDAGCombine(ISD::SHL); 1187 setTargetDAGCombine(ISD::SRA); 1188 setTargetDAGCombine(ISD::SRL); 1189 setTargetDAGCombine(ISD::OR); 1190 setTargetDAGCombine(ISD::AND); 1191 setTargetDAGCombine(ISD::ADD); 1192 setTargetDAGCombine(ISD::FADD); 1193 setTargetDAGCombine(ISD::FSUB); 1194 setTargetDAGCombine(ISD::SUB); 1195 setTargetDAGCombine(ISD::LOAD); 1196 setTargetDAGCombine(ISD::STORE); 1197 setTargetDAGCombine(ISD::ZERO_EXTEND); 1198 setTargetDAGCombine(ISD::SINT_TO_FP); 1199 if (Subtarget->is64Bit()) 1200 setTargetDAGCombine(ISD::MUL); 1201 if (Subtarget->hasBMI()) 1202 setTargetDAGCombine(ISD::XOR); 1203 1204 computeRegisterProperties(); 1205 1206 // On Darwin, -Os means optimize for size without hurting performance, 1207 // do not reduce the limit. 1208 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores 1209 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8; 1210 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores 1211 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1212 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores 1213 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1214 setPrefLoopAlignment(16); 1215 benefitFromCodePlacementOpt = true; 1216 1217 setPrefFunctionAlignment(4); 1218 } 1219 1220 1221 EVT X86TargetLowering::getSetCCResultType(EVT VT) const { 1222 if (!VT.isVector()) return MVT::i8; 1223 return VT.changeVectorElementTypeToInteger(); 1224 } 1225 1226 1227 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1228 /// the desired ByVal argument alignment. 1229 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) { 1230 if (MaxAlign == 16) 1231 return; 1232 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1233 if (VTy->getBitWidth() == 128) 1234 MaxAlign = 16; 1235 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1236 unsigned EltAlign = 0; 1237 getMaxByValAlign(ATy->getElementType(), EltAlign); 1238 if (EltAlign > MaxAlign) 1239 MaxAlign = EltAlign; 1240 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1241 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1242 unsigned EltAlign = 0; 1243 getMaxByValAlign(STy->getElementType(i), EltAlign); 1244 if (EltAlign > MaxAlign) 1245 MaxAlign = EltAlign; 1246 if (MaxAlign == 16) 1247 break; 1248 } 1249 } 1250 return; 1251 } 1252 1253 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1254 /// function arguments in the caller parameter area. For X86, aggregates 1255 /// that contain SSE vectors are placed at 16-byte boundaries while the rest 1256 /// are at 4-byte boundaries. 1257 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const { 1258 if (Subtarget->is64Bit()) { 1259 // Max of 8 and alignment of type. 1260 unsigned TyAlign = TD->getABITypeAlignment(Ty); 1261 if (TyAlign > 8) 1262 return TyAlign; 1263 return 8; 1264 } 1265 1266 unsigned Align = 4; 1267 if (Subtarget->hasXMM()) 1268 getMaxByValAlign(Ty, Align); 1269 return Align; 1270 } 1271 1272 /// getOptimalMemOpType - Returns the target specific optimal type for load 1273 /// and store operations as a result of memset, memcpy, and memmove 1274 /// lowering. If DstAlign is zero that means it's safe to destination 1275 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 1276 /// means there isn't a need to check it against alignment requirement, 1277 /// probably because the source does not need to be loaded. If 1278 /// 'IsZeroVal' is true, that means it's safe to return a 1279 /// non-scalar-integer type, e.g. empty string source, constant, or loaded 1280 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is 1281 /// constant so it does not need to be loaded. 1282 /// It returns EVT::Other if the type should be determined using generic 1283 /// target-independent logic. 1284 EVT 1285 X86TargetLowering::getOptimalMemOpType(uint64_t Size, 1286 unsigned DstAlign, unsigned SrcAlign, 1287 bool IsZeroVal, 1288 bool MemcpyStrSrc, 1289 MachineFunction &MF) const { 1290 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like 1291 // linux. This is because the stack realignment code can't handle certain 1292 // cases like PR2962. This should be removed when PR2962 is fixed. 1293 const Function *F = MF.getFunction(); 1294 if (IsZeroVal && 1295 !F->hasFnAttr(Attribute::NoImplicitFloat)) { 1296 if (Size >= 16 && 1297 (Subtarget->isUnalignedMemAccessFast() || 1298 ((DstAlign == 0 || DstAlign >= 16) && 1299 (SrcAlign == 0 || SrcAlign >= 16))) && 1300 Subtarget->getStackAlignment() >= 16) { 1301 if (Subtarget->hasAVX() && 1302 Subtarget->getStackAlignment() >= 32) 1303 return MVT::v8f32; 1304 if (Subtarget->hasXMMInt()) 1305 return MVT::v4i32; 1306 if (Subtarget->hasXMM()) 1307 return MVT::v4f32; 1308 } else if (!MemcpyStrSrc && Size >= 8 && 1309 !Subtarget->is64Bit() && 1310 Subtarget->getStackAlignment() >= 8 && 1311 Subtarget->hasXMMInt()) { 1312 // Do not use f64 to lower memcpy if source is string constant. It's 1313 // better to use i32 to avoid the loads. 1314 return MVT::f64; 1315 } 1316 } 1317 if (Subtarget->is64Bit() && Size >= 8) 1318 return MVT::i64; 1319 return MVT::i32; 1320 } 1321 1322 /// getJumpTableEncoding - Return the entry encoding for a jump table in the 1323 /// current function. The returned value is a member of the 1324 /// MachineJumpTableInfo::JTEntryKind enum. 1325 unsigned X86TargetLowering::getJumpTableEncoding() const { 1326 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF 1327 // symbol. 1328 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1329 Subtarget->isPICStyleGOT()) 1330 return MachineJumpTableInfo::EK_Custom32; 1331 1332 // Otherwise, use the normal jump table encoding heuristics. 1333 return TargetLowering::getJumpTableEncoding(); 1334 } 1335 1336 const MCExpr * 1337 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 1338 const MachineBasicBlock *MBB, 1339 unsigned uid,MCContext &Ctx) const{ 1340 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1341 Subtarget->isPICStyleGOT()); 1342 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF 1343 // entries. 1344 return MCSymbolRefExpr::Create(MBB->getSymbol(), 1345 MCSymbolRefExpr::VK_GOTOFF, Ctx); 1346 } 1347 1348 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 1349 /// jumptable. 1350 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table, 1351 SelectionDAG &DAG) const { 1352 if (!Subtarget->is64Bit()) 1353 // This doesn't have DebugLoc associated with it, but is not really the 1354 // same as a Register. 1355 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy()); 1356 return Table; 1357 } 1358 1359 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 1360 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 1361 /// MCExpr. 1362 const MCExpr *X86TargetLowering:: 1363 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, 1364 MCContext &Ctx) const { 1365 // X86-64 uses RIP relative addressing based on the jump table label. 1366 if (Subtarget->isPICStyleRIPRel()) 1367 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 1368 1369 // Otherwise, the reference is relative to the PIC base. 1370 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx); 1371 } 1372 1373 // FIXME: Why this routine is here? Move to RegInfo! 1374 std::pair<const TargetRegisterClass*, uint8_t> 1375 X86TargetLowering::findRepresentativeClass(EVT VT) const{ 1376 const TargetRegisterClass *RRC = 0; 1377 uint8_t Cost = 1; 1378 switch (VT.getSimpleVT().SimpleTy) { 1379 default: 1380 return TargetLowering::findRepresentativeClass(VT); 1381 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64: 1382 RRC = (Subtarget->is64Bit() 1383 ? X86::GR64RegisterClass : X86::GR32RegisterClass); 1384 break; 1385 case MVT::x86mmx: 1386 RRC = X86::VR64RegisterClass; 1387 break; 1388 case MVT::f32: case MVT::f64: 1389 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1390 case MVT::v4f32: case MVT::v2f64: 1391 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32: 1392 case MVT::v4f64: 1393 RRC = X86::VR128RegisterClass; 1394 break; 1395 } 1396 return std::make_pair(RRC, Cost); 1397 } 1398 1399 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace, 1400 unsigned &Offset) const { 1401 if (!Subtarget->isTargetLinux()) 1402 return false; 1403 1404 if (Subtarget->is64Bit()) { 1405 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs: 1406 Offset = 0x28; 1407 if (getTargetMachine().getCodeModel() == CodeModel::Kernel) 1408 AddressSpace = 256; 1409 else 1410 AddressSpace = 257; 1411 } else { 1412 // %gs:0x14 on i386 1413 Offset = 0x14; 1414 AddressSpace = 256; 1415 } 1416 return true; 1417 } 1418 1419 1420 //===----------------------------------------------------------------------===// 1421 // Return Value Calling Convention Implementation 1422 //===----------------------------------------------------------------------===// 1423 1424 #include "X86GenCallingConv.inc" 1425 1426 bool 1427 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, 1428 MachineFunction &MF, bool isVarArg, 1429 const SmallVectorImpl<ISD::OutputArg> &Outs, 1430 LLVMContext &Context) const { 1431 SmallVector<CCValAssign, 16> RVLocs; 1432 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1433 RVLocs, Context); 1434 return CCInfo.CheckReturn(Outs, RetCC_X86); 1435 } 1436 1437 SDValue 1438 X86TargetLowering::LowerReturn(SDValue Chain, 1439 CallingConv::ID CallConv, bool isVarArg, 1440 const SmallVectorImpl<ISD::OutputArg> &Outs, 1441 const SmallVectorImpl<SDValue> &OutVals, 1442 DebugLoc dl, SelectionDAG &DAG) const { 1443 MachineFunction &MF = DAG.getMachineFunction(); 1444 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1445 1446 SmallVector<CCValAssign, 16> RVLocs; 1447 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1448 RVLocs, *DAG.getContext()); 1449 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1450 1451 // Add the regs to the liveout set for the function. 1452 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1453 for (unsigned i = 0; i != RVLocs.size(); ++i) 1454 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg())) 1455 MRI.addLiveOut(RVLocs[i].getLocReg()); 1456 1457 SDValue Flag; 1458 1459 SmallVector<SDValue, 6> RetOps; 1460 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1461 // Operand #1 = Bytes To Pop 1462 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), 1463 MVT::i16)); 1464 1465 // Copy the result values into the output registers. 1466 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1467 CCValAssign &VA = RVLocs[i]; 1468 assert(VA.isRegLoc() && "Can only return in registers!"); 1469 SDValue ValToCopy = OutVals[i]; 1470 EVT ValVT = ValToCopy.getValueType(); 1471 1472 // If this is x86-64, and we disabled SSE, we can't return FP values, 1473 // or SSE or MMX vectors. 1474 if ((ValVT == MVT::f32 || ValVT == MVT::f64 || 1475 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && 1476 (Subtarget->is64Bit() && !Subtarget->hasXMM())) { 1477 report_fatal_error("SSE register return with SSE disabled"); 1478 } 1479 // Likewise we can't return F64 values with SSE1 only. gcc does so, but 1480 // llvm-gcc has never done it right and no one has noticed, so this 1481 // should be OK for now. 1482 if (ValVT == MVT::f64 && 1483 (Subtarget->is64Bit() && !Subtarget->hasXMMInt())) 1484 report_fatal_error("SSE2 register return with SSE2 disabled"); 1485 1486 // Returns in ST0/ST1 are handled specially: these are pushed as operands to 1487 // the RET instruction and handled by the FP Stackifier. 1488 if (VA.getLocReg() == X86::ST0 || 1489 VA.getLocReg() == X86::ST1) { 1490 // If this is a copy from an xmm register to ST(0), use an FPExtend to 1491 // change the value to the FP stack register class. 1492 if (isScalarFPTypeInSSEReg(VA.getValVT())) 1493 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy); 1494 RetOps.push_back(ValToCopy); 1495 // Don't emit a copytoreg. 1496 continue; 1497 } 1498 1499 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64 1500 // which is returned in RAX / RDX. 1501 if (Subtarget->is64Bit()) { 1502 if (ValVT == MVT::x86mmx) { 1503 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1504 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy); 1505 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 1506 ValToCopy); 1507 // If we don't have SSE2 available, convert to v4f32 so the generated 1508 // register is legal. 1509 if (!Subtarget->hasXMMInt()) 1510 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy); 1511 } 1512 } 1513 } 1514 1515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag); 1516 Flag = Chain.getValue(1); 1517 } 1518 1519 // The x86-64 ABI for returning structs by value requires that we copy 1520 // the sret argument into %rax for the return. We saved the argument into 1521 // a virtual register in the entry block, so now we copy the value out 1522 // and into %rax. 1523 if (Subtarget->is64Bit() && 1524 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) { 1525 MachineFunction &MF = DAG.getMachineFunction(); 1526 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1527 unsigned Reg = FuncInfo->getSRetReturnReg(); 1528 assert(Reg && 1529 "SRetReturnReg should have been set in LowerFormalArguments()."); 1530 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy()); 1531 1532 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag); 1533 Flag = Chain.getValue(1); 1534 1535 // RAX now acts like a return value. 1536 MRI.addLiveOut(X86::RAX); 1537 } 1538 1539 RetOps[0] = Chain; // Update chain. 1540 1541 // Add the flag if we have it. 1542 if (Flag.getNode()) 1543 RetOps.push_back(Flag); 1544 1545 return DAG.getNode(X86ISD::RET_FLAG, dl, 1546 MVT::Other, &RetOps[0], RetOps.size()); 1547 } 1548 1549 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const { 1550 if (N->getNumValues() != 1) 1551 return false; 1552 if (!N->hasNUsesOfValue(1, 0)) 1553 return false; 1554 1555 SDNode *Copy = *N->use_begin(); 1556 if (Copy->getOpcode() != ISD::CopyToReg && 1557 Copy->getOpcode() != ISD::FP_EXTEND) 1558 return false; 1559 1560 bool HasRet = false; 1561 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 1562 UI != UE; ++UI) { 1563 if (UI->getOpcode() != X86ISD::RET_FLAG) 1564 return false; 1565 HasRet = true; 1566 } 1567 1568 return HasRet; 1569 } 1570 1571 EVT 1572 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT, 1573 ISD::NodeType ExtendKind) const { 1574 MVT ReturnMVT; 1575 // TODO: Is this also valid on 32-bit? 1576 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND) 1577 ReturnMVT = MVT::i8; 1578 else 1579 ReturnMVT = MVT::i32; 1580 1581 EVT MinVT = getRegisterType(Context, ReturnMVT); 1582 return VT.bitsLT(MinVT) ? MinVT : VT; 1583 } 1584 1585 /// LowerCallResult - Lower the result values of a call into the 1586 /// appropriate copies out of appropriate physical registers. 1587 /// 1588 SDValue 1589 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1590 CallingConv::ID CallConv, bool isVarArg, 1591 const SmallVectorImpl<ISD::InputArg> &Ins, 1592 DebugLoc dl, SelectionDAG &DAG, 1593 SmallVectorImpl<SDValue> &InVals) const { 1594 1595 // Assign locations to each value returned by this call. 1596 SmallVector<CCValAssign, 16> RVLocs; 1597 bool Is64Bit = Subtarget->is64Bit(); 1598 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1599 getTargetMachine(), RVLocs, *DAG.getContext()); 1600 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 1601 1602 // Copy all of the result registers out of their specified physreg. 1603 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1604 CCValAssign &VA = RVLocs[i]; 1605 EVT CopyVT = VA.getValVT(); 1606 1607 // If this is x86-64, and we disabled SSE, we can't return FP values 1608 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 1609 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) { 1610 report_fatal_error("SSE register return with SSE disabled"); 1611 } 1612 1613 SDValue Val; 1614 1615 // If this is a call to a function that returns an fp value on the floating 1616 // point stack, we must guarantee the the value is popped from the stack, so 1617 // a CopyFromReg is not good enough - the copy instruction may be eliminated 1618 // if the return value is not used. We use the FpPOP_RETVAL instruction 1619 // instead. 1620 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 1621 // If we prefer to use the value in xmm registers, copy it out as f80 and 1622 // use a truncate to move it from fp stack reg to xmm reg. 1623 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80; 1624 SDValue Ops[] = { Chain, InFlag }; 1625 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT, 1626 MVT::Other, MVT::Glue, Ops, 2), 1); 1627 Val = Chain.getValue(0); 1628 1629 // Round the f80 to the right size, which also moves it to the appropriate 1630 // xmm register. 1631 if (CopyVT != VA.getValVT()) 1632 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val, 1633 // This truncation won't change the value. 1634 DAG.getIntPtrConstant(1)); 1635 } else { 1636 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1637 CopyVT, InFlag).getValue(1); 1638 Val = Chain.getValue(0); 1639 } 1640 InFlag = Chain.getValue(2); 1641 InVals.push_back(Val); 1642 } 1643 1644 return Chain; 1645 } 1646 1647 1648 //===----------------------------------------------------------------------===// 1649 // C & StdCall & Fast Calling Convention implementation 1650 //===----------------------------------------------------------------------===// 1651 // StdCall calling convention seems to be standard for many Windows' API 1652 // routines and around. It differs from C calling convention just a little: 1653 // callee should clean up the stack, not caller. Symbols should be also 1654 // decorated in some fancy way :) It doesn't support any vector arguments. 1655 // For info on fast calling convention see Fast Calling Convention (tail call) 1656 // implementation LowerX86_32FastCCCallTo. 1657 1658 /// CallIsStructReturn - Determines whether a call uses struct return 1659 /// semantics. 1660 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) { 1661 if (Outs.empty()) 1662 return false; 1663 1664 return Outs[0].Flags.isSRet(); 1665 } 1666 1667 /// ArgsAreStructReturn - Determines whether a function uses struct 1668 /// return semantics. 1669 static bool 1670 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) { 1671 if (Ins.empty()) 1672 return false; 1673 1674 return Ins[0].Flags.isSRet(); 1675 } 1676 1677 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 1678 /// by "Src" to address "Dst" with size and alignment information specified by 1679 /// the specific parameter attribute. The copy will be passed as a byval 1680 /// function parameter. 1681 static SDValue 1682 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 1683 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 1684 DebugLoc dl) { 1685 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 1686 1687 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 1688 /*isVolatile*/false, /*AlwaysInline=*/true, 1689 MachinePointerInfo(), MachinePointerInfo()); 1690 } 1691 1692 /// IsTailCallConvention - Return true if the calling convention is one that 1693 /// supports tail call optimization. 1694 static bool IsTailCallConvention(CallingConv::ID CC) { 1695 return (CC == CallingConv::Fast || CC == CallingConv::GHC); 1696 } 1697 1698 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 1699 if (!CI->isTailCall()) 1700 return false; 1701 1702 CallSite CS(CI); 1703 CallingConv::ID CalleeCC = CS.getCallingConv(); 1704 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C) 1705 return false; 1706 1707 return true; 1708 } 1709 1710 /// FuncIsMadeTailCallSafe - Return true if the function is being made into 1711 /// a tailcall target by changing its ABI. 1712 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) { 1713 return GuaranteedTailCallOpt && IsTailCallConvention(CC); 1714 } 1715 1716 SDValue 1717 X86TargetLowering::LowerMemArgument(SDValue Chain, 1718 CallingConv::ID CallConv, 1719 const SmallVectorImpl<ISD::InputArg> &Ins, 1720 DebugLoc dl, SelectionDAG &DAG, 1721 const CCValAssign &VA, 1722 MachineFrameInfo *MFI, 1723 unsigned i) const { 1724 // Create the nodes corresponding to a load from this parameter slot. 1725 ISD::ArgFlagsTy Flags = Ins[i].Flags; 1726 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv); 1727 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal(); 1728 EVT ValVT; 1729 1730 // If value is passed by pointer we have address passed instead of the value 1731 // itself. 1732 if (VA.getLocInfo() == CCValAssign::Indirect) 1733 ValVT = VA.getLocVT(); 1734 else 1735 ValVT = VA.getValVT(); 1736 1737 // FIXME: For now, all byval parameter objects are marked mutable. This can be 1738 // changed with more analysis. 1739 // In case of tail call optimization mark all arguments mutable. Since they 1740 // could be overwritten by lowering of arguments in case of a tail call. 1741 if (Flags.isByVal()) { 1742 unsigned Bytes = Flags.getByValSize(); 1743 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects. 1744 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable); 1745 return DAG.getFrameIndex(FI, getPointerTy()); 1746 } else { 1747 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8, 1748 VA.getLocMemOffset(), isImmutable); 1749 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 1750 return DAG.getLoad(ValVT, dl, Chain, FIN, 1751 MachinePointerInfo::getFixedStack(FI), 1752 false, false, false, 0); 1753 } 1754 } 1755 1756 SDValue 1757 X86TargetLowering::LowerFormalArguments(SDValue Chain, 1758 CallingConv::ID CallConv, 1759 bool isVarArg, 1760 const SmallVectorImpl<ISD::InputArg> &Ins, 1761 DebugLoc dl, 1762 SelectionDAG &DAG, 1763 SmallVectorImpl<SDValue> &InVals) 1764 const { 1765 MachineFunction &MF = DAG.getMachineFunction(); 1766 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1767 1768 const Function* Fn = MF.getFunction(); 1769 if (Fn->hasExternalLinkage() && 1770 Subtarget->isTargetCygMing() && 1771 Fn->getName() == "main") 1772 FuncInfo->setForceFramePointer(true); 1773 1774 MachineFrameInfo *MFI = MF.getFrameInfo(); 1775 bool Is64Bit = Subtarget->is64Bit(); 1776 bool IsWin64 = Subtarget->isTargetWin64(); 1777 1778 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1779 "Var args not supported with calling convention fastcc or ghc"); 1780 1781 // Assign locations to all of the incoming arguments. 1782 SmallVector<CCValAssign, 16> ArgLocs; 1783 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1784 ArgLocs, *DAG.getContext()); 1785 1786 // Allocate shadow area for Win64 1787 if (IsWin64) { 1788 CCInfo.AllocateStack(32, 8); 1789 } 1790 1791 CCInfo.AnalyzeFormalArguments(Ins, CC_X86); 1792 1793 unsigned LastVal = ~0U; 1794 SDValue ArgValue; 1795 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1796 CCValAssign &VA = ArgLocs[i]; 1797 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later 1798 // places. 1799 assert(VA.getValNo() != LastVal && 1800 "Don't support value assigned to multiple locs yet"); 1801 (void)LastVal; 1802 LastVal = VA.getValNo(); 1803 1804 if (VA.isRegLoc()) { 1805 EVT RegVT = VA.getLocVT(); 1806 TargetRegisterClass *RC = NULL; 1807 if (RegVT == MVT::i32) 1808 RC = X86::GR32RegisterClass; 1809 else if (Is64Bit && RegVT == MVT::i64) 1810 RC = X86::GR64RegisterClass; 1811 else if (RegVT == MVT::f32) 1812 RC = X86::FR32RegisterClass; 1813 else if (RegVT == MVT::f64) 1814 RC = X86::FR64RegisterClass; 1815 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256) 1816 RC = X86::VR256RegisterClass; 1817 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128) 1818 RC = X86::VR128RegisterClass; 1819 else if (RegVT == MVT::x86mmx) 1820 RC = X86::VR64RegisterClass; 1821 else 1822 llvm_unreachable("Unknown argument type!"); 1823 1824 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 1825 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 1826 1827 // If this is an 8 or 16-bit value, it is really passed promoted to 32 1828 // bits. Insert an assert[sz]ext to capture this, then truncate to the 1829 // right size. 1830 if (VA.getLocInfo() == CCValAssign::SExt) 1831 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 1832 DAG.getValueType(VA.getValVT())); 1833 else if (VA.getLocInfo() == CCValAssign::ZExt) 1834 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 1835 DAG.getValueType(VA.getValVT())); 1836 else if (VA.getLocInfo() == CCValAssign::BCvt) 1837 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 1838 1839 if (VA.isExtInLoc()) { 1840 // Handle MMX values passed in XMM regs. 1841 if (RegVT.isVector()) { 1842 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), 1843 ArgValue); 1844 } else 1845 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1846 } 1847 } else { 1848 assert(VA.isMemLoc()); 1849 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i); 1850 } 1851 1852 // If value is passed via pointer - do a load. 1853 if (VA.getLocInfo() == CCValAssign::Indirect) 1854 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, 1855 MachinePointerInfo(), false, false, false, 0); 1856 1857 InVals.push_back(ArgValue); 1858 } 1859 1860 // The x86-64 ABI for returning structs by value requires that we copy 1861 // the sret argument into %rax for the return. Save the argument into 1862 // a virtual register so that we can access it from the return points. 1863 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) { 1864 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1865 unsigned Reg = FuncInfo->getSRetReturnReg(); 1866 if (!Reg) { 1867 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64)); 1868 FuncInfo->setSRetReturnReg(Reg); 1869 } 1870 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]); 1871 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain); 1872 } 1873 1874 unsigned StackSize = CCInfo.getNextStackOffset(); 1875 // Align stack specially for tail calls. 1876 if (FuncIsMadeTailCallSafe(CallConv)) 1877 StackSize = GetAlignedArgumentStackSize(StackSize, DAG); 1878 1879 // If the function takes variable number of arguments, make a frame index for 1880 // the start of the first vararg value... for expansion of llvm.va_start. 1881 if (isVarArg) { 1882 if (Is64Bit || (CallConv != CallingConv::X86_FastCall && 1883 CallConv != CallingConv::X86_ThisCall)) { 1884 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true)); 1885 } 1886 if (Is64Bit) { 1887 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0; 1888 1889 // FIXME: We should really autogenerate these arrays 1890 static const unsigned GPR64ArgRegsWin64[] = { 1891 X86::RCX, X86::RDX, X86::R8, X86::R9 1892 }; 1893 static const unsigned GPR64ArgRegs64Bit[] = { 1894 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9 1895 }; 1896 static const unsigned XMMArgRegs64Bit[] = { 1897 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 1898 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 1899 }; 1900 const unsigned *GPR64ArgRegs; 1901 unsigned NumXMMRegs = 0; 1902 1903 if (IsWin64) { 1904 // The XMM registers which might contain var arg parameters are shadowed 1905 // in their paired GPR. So we only need to save the GPR to their home 1906 // slots. 1907 TotalNumIntRegs = 4; 1908 GPR64ArgRegs = GPR64ArgRegsWin64; 1909 } else { 1910 TotalNumIntRegs = 6; TotalNumXMMRegs = 8; 1911 GPR64ArgRegs = GPR64ArgRegs64Bit; 1912 1913 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs); 1914 } 1915 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 1916 TotalNumIntRegs); 1917 1918 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat); 1919 assert(!(NumXMMRegs && !Subtarget->hasXMM()) && 1920 "SSE register cannot be used when SSE is disabled!"); 1921 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) && 1922 "SSE register cannot be used when SSE is disabled!"); 1923 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM()) 1924 // Kernel mode asks for SSE to be disabled, so don't push them 1925 // on the stack. 1926 TotalNumXMMRegs = 0; 1927 1928 if (IsWin64) { 1929 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering(); 1930 // Get to the caller-allocated home save location. Add 8 to account 1931 // for the return address. 1932 int HomeOffset = TFI.getOffsetOfLocalArea() + 8; 1933 FuncInfo->setRegSaveFrameIndex( 1934 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false)); 1935 // Fixup to set vararg frame on shadow area (4 x i64). 1936 if (NumIntRegs < 4) 1937 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex()); 1938 } else { 1939 // For X86-64, if there are vararg parameters that are passed via 1940 // registers, then we must store them to their spots on the stack so they 1941 // may be loaded by deferencing the result of va_next. 1942 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8); 1943 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16); 1944 FuncInfo->setRegSaveFrameIndex( 1945 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16, 1946 false)); 1947 } 1948 1949 // Store the integer parameter registers. 1950 SmallVector<SDValue, 8> MemOps; 1951 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 1952 getPointerTy()); 1953 unsigned Offset = FuncInfo->getVarArgsGPOffset(); 1954 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) { 1955 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN, 1956 DAG.getIntPtrConstant(Offset)); 1957 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs], 1958 X86::GR64RegisterClass); 1959 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 1960 SDValue Store = 1961 DAG.getStore(Val.getValue(1), dl, Val, FIN, 1962 MachinePointerInfo::getFixedStack( 1963 FuncInfo->getRegSaveFrameIndex(), Offset), 1964 false, false, 0); 1965 MemOps.push_back(Store); 1966 Offset += 8; 1967 } 1968 1969 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) { 1970 // Now store the XMM (fp + vector) parameter registers. 1971 SmallVector<SDValue, 11> SaveXMMOps; 1972 SaveXMMOps.push_back(Chain); 1973 1974 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass); 1975 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8); 1976 SaveXMMOps.push_back(ALVal); 1977 1978 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1979 FuncInfo->getRegSaveFrameIndex())); 1980 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1981 FuncInfo->getVarArgsFPOffset())); 1982 1983 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) { 1984 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs], 1985 X86::VR128RegisterClass); 1986 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32); 1987 SaveXMMOps.push_back(Val); 1988 } 1989 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, 1990 MVT::Other, 1991 &SaveXMMOps[0], SaveXMMOps.size())); 1992 } 1993 1994 if (!MemOps.empty()) 1995 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 1996 &MemOps[0], MemOps.size()); 1997 } 1998 } 1999 2000 // Some CCs need callee pop. 2001 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) { 2002 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything. 2003 } else { 2004 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing. 2005 // If this is an sret function, the return should pop the hidden pointer. 2006 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins)) 2007 FuncInfo->setBytesToPopOnReturn(4); 2008 } 2009 2010 if (!Is64Bit) { 2011 // RegSaveFrameIndex is X86-64 only. 2012 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA); 2013 if (CallConv == CallingConv::X86_FastCall || 2014 CallConv == CallingConv::X86_ThisCall) 2015 // fastcc functions can't have varargs. 2016 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA); 2017 } 2018 2019 FuncInfo->setArgumentStackSize(StackSize); 2020 2021 return Chain; 2022 } 2023 2024 SDValue 2025 X86TargetLowering::LowerMemOpCallTo(SDValue Chain, 2026 SDValue StackPtr, SDValue Arg, 2027 DebugLoc dl, SelectionDAG &DAG, 2028 const CCValAssign &VA, 2029 ISD::ArgFlagsTy Flags) const { 2030 unsigned LocMemOffset = VA.getLocMemOffset(); 2031 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 2032 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 2033 if (Flags.isByVal()) 2034 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl); 2035 2036 return DAG.getStore(Chain, dl, Arg, PtrOff, 2037 MachinePointerInfo::getStack(LocMemOffset), 2038 false, false, 0); 2039 } 2040 2041 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call 2042 /// optimization is performed and it is required. 2043 SDValue 2044 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 2045 SDValue &OutRetAddr, SDValue Chain, 2046 bool IsTailCall, bool Is64Bit, 2047 int FPDiff, DebugLoc dl) const { 2048 // Adjust the Return address stack slot. 2049 EVT VT = getPointerTy(); 2050 OutRetAddr = getReturnAddressFrameIndex(DAG); 2051 2052 // Load the "old" Return address. 2053 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(), 2054 false, false, false, 0); 2055 return SDValue(OutRetAddr.getNode(), 1); 2056 } 2057 2058 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call 2059 /// optimization is performed and it is required (FPDiff!=0). 2060 static SDValue 2061 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 2062 SDValue Chain, SDValue RetAddrFrIdx, 2063 bool Is64Bit, int FPDiff, DebugLoc dl) { 2064 // Store the return address to the appropriate stack slot. 2065 if (!FPDiff) return Chain; 2066 // Calculate the new stack slot for the return address. 2067 int SlotSize = Is64Bit ? 8 : 4; 2068 int NewReturnAddrFI = 2069 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false); 2070 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2071 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT); 2072 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx, 2073 MachinePointerInfo::getFixedStack(NewReturnAddrFI), 2074 false, false, 0); 2075 return Chain; 2076 } 2077 2078 SDValue 2079 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee, 2080 CallingConv::ID CallConv, bool isVarArg, 2081 bool &isTailCall, 2082 const SmallVectorImpl<ISD::OutputArg> &Outs, 2083 const SmallVectorImpl<SDValue> &OutVals, 2084 const SmallVectorImpl<ISD::InputArg> &Ins, 2085 DebugLoc dl, SelectionDAG &DAG, 2086 SmallVectorImpl<SDValue> &InVals) const { 2087 MachineFunction &MF = DAG.getMachineFunction(); 2088 bool Is64Bit = Subtarget->is64Bit(); 2089 bool IsWin64 = Subtarget->isTargetWin64(); 2090 bool IsStructRet = CallIsStructReturn(Outs); 2091 bool IsSibcall = false; 2092 2093 if (isTailCall) { 2094 // Check if it's really possible to do a tail call. 2095 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 2096 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(), 2097 Outs, OutVals, Ins, DAG); 2098 2099 // Sibcalls are automatically detected tailcalls which do not require 2100 // ABI changes. 2101 if (!GuaranteedTailCallOpt && isTailCall) 2102 IsSibcall = true; 2103 2104 if (isTailCall) 2105 ++NumTailCalls; 2106 } 2107 2108 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 2109 "Var args not supported with calling convention fastcc or ghc"); 2110 2111 // Analyze operands of the call, assigning locations to each operand. 2112 SmallVector<CCValAssign, 16> ArgLocs; 2113 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 2114 ArgLocs, *DAG.getContext()); 2115 2116 // Allocate shadow area for Win64 2117 if (IsWin64) { 2118 CCInfo.AllocateStack(32, 8); 2119 } 2120 2121 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2122 2123 // Get a count of how many bytes are to be pushed on the stack. 2124 unsigned NumBytes = CCInfo.getNextStackOffset(); 2125 if (IsSibcall) 2126 // This is a sibcall. The memory operands are available in caller's 2127 // own caller's stack. 2128 NumBytes = 0; 2129 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv)) 2130 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG); 2131 2132 int FPDiff = 0; 2133 if (isTailCall && !IsSibcall) { 2134 // Lower arguments at fp - stackoffset + fpdiff. 2135 unsigned NumBytesCallerPushed = 2136 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn(); 2137 FPDiff = NumBytesCallerPushed - NumBytes; 2138 2139 // Set the delta of movement of the returnaddr stackslot. 2140 // But only set if delta is greater than previous delta. 2141 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta())) 2142 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff); 2143 } 2144 2145 if (!IsSibcall) 2146 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true)); 2147 2148 SDValue RetAddrFrIdx; 2149 // Load return address for tail calls. 2150 if (isTailCall && FPDiff) 2151 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, 2152 Is64Bit, FPDiff, dl); 2153 2154 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2155 SmallVector<SDValue, 8> MemOpChains; 2156 SDValue StackPtr; 2157 2158 // Walk the register/memloc assignments, inserting copies/loads. In the case 2159 // of tail call optimization arguments are handle later. 2160 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2161 CCValAssign &VA = ArgLocs[i]; 2162 EVT RegVT = VA.getLocVT(); 2163 SDValue Arg = OutVals[i]; 2164 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2165 bool isByVal = Flags.isByVal(); 2166 2167 // Promote the value if needed. 2168 switch (VA.getLocInfo()) { 2169 default: llvm_unreachable("Unknown loc info!"); 2170 case CCValAssign::Full: break; 2171 case CCValAssign::SExt: 2172 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg); 2173 break; 2174 case CCValAssign::ZExt: 2175 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg); 2176 break; 2177 case CCValAssign::AExt: 2178 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) { 2179 // Special case: passing MMX values in XMM registers. 2180 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 2181 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg); 2182 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg); 2183 } else 2184 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg); 2185 break; 2186 case CCValAssign::BCvt: 2187 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg); 2188 break; 2189 case CCValAssign::Indirect: { 2190 // Store the argument. 2191 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT()); 2192 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2193 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot, 2194 MachinePointerInfo::getFixedStack(FI), 2195 false, false, 0); 2196 Arg = SpillSlot; 2197 break; 2198 } 2199 } 2200 2201 if (VA.isRegLoc()) { 2202 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2203 if (isVarArg && IsWin64) { 2204 // Win64 ABI requires argument XMM reg to be copied to the corresponding 2205 // shadow reg if callee is a varargs function. 2206 unsigned ShadowReg = 0; 2207 switch (VA.getLocReg()) { 2208 case X86::XMM0: ShadowReg = X86::RCX; break; 2209 case X86::XMM1: ShadowReg = X86::RDX; break; 2210 case X86::XMM2: ShadowReg = X86::R8; break; 2211 case X86::XMM3: ShadowReg = X86::R9; break; 2212 } 2213 if (ShadowReg) 2214 RegsToPass.push_back(std::make_pair(ShadowReg, Arg)); 2215 } 2216 } else if (!IsSibcall && (!isTailCall || isByVal)) { 2217 assert(VA.isMemLoc()); 2218 if (StackPtr.getNode() == 0) 2219 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy()); 2220 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2221 dl, DAG, VA, Flags)); 2222 } 2223 } 2224 2225 if (!MemOpChains.empty()) 2226 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2227 &MemOpChains[0], MemOpChains.size()); 2228 2229 // Build a sequence of copy-to-reg nodes chained together with token chain 2230 // and flag operands which copy the outgoing args into registers. 2231 SDValue InFlag; 2232 // Tail call byval lowering might overwrite argument registers so in case of 2233 // tail call optimization the copies to registers are lowered later. 2234 if (!isTailCall) 2235 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2236 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2237 RegsToPass[i].second, InFlag); 2238 InFlag = Chain.getValue(1); 2239 } 2240 2241 if (Subtarget->isPICStyleGOT()) { 2242 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2243 // GOT pointer. 2244 if (!isTailCall) { 2245 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX, 2246 DAG.getNode(X86ISD::GlobalBaseReg, 2247 DebugLoc(), getPointerTy()), 2248 InFlag); 2249 InFlag = Chain.getValue(1); 2250 } else { 2251 // If we are tail calling and generating PIC/GOT style code load the 2252 // address of the callee into ECX. The value in ecx is used as target of 2253 // the tail jump. This is done to circumvent the ebx/callee-saved problem 2254 // for tail calls on PIC/GOT architectures. Normally we would just put the 2255 // address of GOT into ebx and then call target@PLT. But for tail calls 2256 // ebx would be restored (since ebx is callee saved) before jumping to the 2257 // target@PLT. 2258 2259 // Note: The actual moving to ECX is done further down. 2260 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 2261 if (G && !G->getGlobal()->hasHiddenVisibility() && 2262 !G->getGlobal()->hasProtectedVisibility()) 2263 Callee = LowerGlobalAddress(Callee, DAG); 2264 else if (isa<ExternalSymbolSDNode>(Callee)) 2265 Callee = LowerExternalSymbol(Callee, DAG); 2266 } 2267 } 2268 2269 if (Is64Bit && isVarArg && !IsWin64) { 2270 // From AMD64 ABI document: 2271 // For calls that may call functions that use varargs or stdargs 2272 // (prototype-less calls or calls to functions containing ellipsis (...) in 2273 // the declaration) %al is used as hidden argument to specify the number 2274 // of SSE registers used. The contents of %al do not need to match exactly 2275 // the number of registers, but must be an ubound on the number of SSE 2276 // registers used and is in the range 0 - 8 inclusive. 2277 2278 // Count the number of XMM registers allocated. 2279 static const unsigned XMMArgRegs[] = { 2280 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2281 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2282 }; 2283 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2284 assert((Subtarget->hasXMM() || !NumXMMRegs) 2285 && "SSE registers cannot be used when SSE is disabled"); 2286 2287 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, 2288 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag); 2289 InFlag = Chain.getValue(1); 2290 } 2291 2292 2293 // For tail calls lower the arguments to the 'real' stack slot. 2294 if (isTailCall) { 2295 // Force all the incoming stack arguments to be loaded from the stack 2296 // before any new outgoing arguments are stored to the stack, because the 2297 // outgoing stack slots may alias the incoming argument stack slots, and 2298 // the alias isn't otherwise explicit. This is slightly more conservative 2299 // than necessary, because it means that each store effectively depends 2300 // on every argument instead of just those arguments it would clobber. 2301 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain); 2302 2303 SmallVector<SDValue, 8> MemOpChains2; 2304 SDValue FIN; 2305 int FI = 0; 2306 // Do not flag preceding copytoreg stuff together with the following stuff. 2307 InFlag = SDValue(); 2308 if (GuaranteedTailCallOpt) { 2309 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2310 CCValAssign &VA = ArgLocs[i]; 2311 if (VA.isRegLoc()) 2312 continue; 2313 assert(VA.isMemLoc()); 2314 SDValue Arg = OutVals[i]; 2315 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2316 // Create frame index. 2317 int32_t Offset = VA.getLocMemOffset()+FPDiff; 2318 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8; 2319 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2320 FIN = DAG.getFrameIndex(FI, getPointerTy()); 2321 2322 if (Flags.isByVal()) { 2323 // Copy relative to framepointer. 2324 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset()); 2325 if (StackPtr.getNode() == 0) 2326 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, 2327 getPointerTy()); 2328 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source); 2329 2330 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, 2331 ArgChain, 2332 Flags, DAG, dl)); 2333 } else { 2334 // Store relative to framepointer. 2335 MemOpChains2.push_back( 2336 DAG.getStore(ArgChain, dl, Arg, FIN, 2337 MachinePointerInfo::getFixedStack(FI), 2338 false, false, 0)); 2339 } 2340 } 2341 } 2342 2343 if (!MemOpChains2.empty()) 2344 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2345 &MemOpChains2[0], MemOpChains2.size()); 2346 2347 // Copy arguments to their registers. 2348 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2349 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2350 RegsToPass[i].second, InFlag); 2351 InFlag = Chain.getValue(1); 2352 } 2353 InFlag =SDValue(); 2354 2355 // Store the return address to the appropriate stack slot. 2356 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit, 2357 FPDiff, dl); 2358 } 2359 2360 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 2361 assert(Is64Bit && "Large code model is only legal in 64-bit mode."); 2362 // In the 64-bit large code model, we have to make all calls 2363 // through a register, since the call instruction's 32-bit 2364 // pc-relative offset may not be large enough to hold the whole 2365 // address. 2366 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2367 // If the callee is a GlobalAddress node (quite common, every direct call 2368 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack 2369 // it. 2370 2371 // We should use extra load for direct calls to dllimported functions in 2372 // non-JIT mode. 2373 const GlobalValue *GV = G->getGlobal(); 2374 if (!GV->hasDLLImportLinkage()) { 2375 unsigned char OpFlags = 0; 2376 bool ExtraLoad = false; 2377 unsigned WrapperKind = ISD::DELETED_NODE; 2378 2379 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2380 // external symbols most go through the PLT in PIC mode. If the symbol 2381 // has hidden or protected visibility, or if it is static or local, then 2382 // we don't need to use the PLT - we can directly call it. 2383 if (Subtarget->isTargetELF() && 2384 getTargetMachine().getRelocationModel() == Reloc::PIC_ && 2385 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2386 OpFlags = X86II::MO_PLT; 2387 } else if (Subtarget->isPICStyleStubAny() && 2388 (GV->isDeclaration() || GV->isWeakForLinker()) && 2389 (!Subtarget->getTargetTriple().isMacOSX() || 2390 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2391 // PC-relative references to external symbols should go through $stub, 2392 // unless we're building with the leopard linker or later, which 2393 // automatically synthesizes these stubs. 2394 OpFlags = X86II::MO_DARWIN_STUB; 2395 } else if (Subtarget->isPICStyleRIPRel() && 2396 isa<Function>(GV) && 2397 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) { 2398 // If the function is marked as non-lazy, generate an indirect call 2399 // which loads from the GOT directly. This avoids runtime overhead 2400 // at the cost of eager binding (and one extra byte of encoding). 2401 OpFlags = X86II::MO_GOTPCREL; 2402 WrapperKind = X86ISD::WrapperRIP; 2403 ExtraLoad = true; 2404 } 2405 2406 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 2407 G->getOffset(), OpFlags); 2408 2409 // Add a wrapper if needed. 2410 if (WrapperKind != ISD::DELETED_NODE) 2411 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee); 2412 // Add extra indirection if needed. 2413 if (ExtraLoad) 2414 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee, 2415 MachinePointerInfo::getGOT(), 2416 false, false, false, 0); 2417 } 2418 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2419 unsigned char OpFlags = 0; 2420 2421 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to 2422 // external symbols should go through the PLT. 2423 if (Subtarget->isTargetELF() && 2424 getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2425 OpFlags = X86II::MO_PLT; 2426 } else if (Subtarget->isPICStyleStubAny() && 2427 (!Subtarget->getTargetTriple().isMacOSX() || 2428 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2429 // PC-relative references to external symbols should go through $stub, 2430 // unless we're building with the leopard linker or later, which 2431 // automatically synthesizes these stubs. 2432 OpFlags = X86II::MO_DARWIN_STUB; 2433 } 2434 2435 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(), 2436 OpFlags); 2437 } 2438 2439 // Returns a chain & a flag for retval copy to use. 2440 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2441 SmallVector<SDValue, 8> Ops; 2442 2443 if (!IsSibcall && isTailCall) { 2444 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2445 DAG.getIntPtrConstant(0, true), InFlag); 2446 InFlag = Chain.getValue(1); 2447 } 2448 2449 Ops.push_back(Chain); 2450 Ops.push_back(Callee); 2451 2452 if (isTailCall) 2453 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32)); 2454 2455 // Add argument registers to the end of the list so that they are known live 2456 // into the call. 2457 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2458 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2459 RegsToPass[i].second.getValueType())); 2460 2461 // Add an implicit use GOT pointer in EBX. 2462 if (!isTailCall && Subtarget->isPICStyleGOT()) 2463 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy())); 2464 2465 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions. 2466 if (Is64Bit && isVarArg && !IsWin64) 2467 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8)); 2468 2469 if (InFlag.getNode()) 2470 Ops.push_back(InFlag); 2471 2472 if (isTailCall) { 2473 // We used to do: 2474 //// If this is the first return lowered for this function, add the regs 2475 //// to the liveout set for the function. 2476 // This isn't right, although it's probably harmless on x86; liveouts 2477 // should be computed from returns not tail calls. Consider a void 2478 // function making a tail call to a function returning int. 2479 return DAG.getNode(X86ISD::TC_RETURN, dl, 2480 NodeTys, &Ops[0], Ops.size()); 2481 } 2482 2483 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); 2484 InFlag = Chain.getValue(1); 2485 2486 // Create the CALLSEQ_END node. 2487 unsigned NumBytesForCalleeToPush; 2488 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) 2489 NumBytesForCalleeToPush = NumBytes; // Callee pops everything 2490 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet) 2491 // If this is a call to a struct-return function, the callee 2492 // pops the hidden struct pointer, so we have to push it back. 2493 // This is common for Darwin/X86, Linux & Mingw32 targets. 2494 NumBytesForCalleeToPush = 4; 2495 else 2496 NumBytesForCalleeToPush = 0; // Callee pops nothing. 2497 2498 // Returns a flag for retval copy to use. 2499 if (!IsSibcall) { 2500 Chain = DAG.getCALLSEQ_END(Chain, 2501 DAG.getIntPtrConstant(NumBytes, true), 2502 DAG.getIntPtrConstant(NumBytesForCalleeToPush, 2503 true), 2504 InFlag); 2505 InFlag = Chain.getValue(1); 2506 } 2507 2508 // Handle result values, copying them out of physregs into vregs that we 2509 // return. 2510 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2511 Ins, dl, DAG, InVals); 2512 } 2513 2514 2515 //===----------------------------------------------------------------------===// 2516 // Fast Calling Convention (tail call) implementation 2517 //===----------------------------------------------------------------------===// 2518 2519 // Like std call, callee cleans arguments, convention except that ECX is 2520 // reserved for storing the tail called function address. Only 2 registers are 2521 // free for argument passing (inreg). Tail call optimization is performed 2522 // provided: 2523 // * tailcallopt is enabled 2524 // * caller/callee are fastcc 2525 // On X86_64 architecture with GOT-style position independent code only local 2526 // (within module) calls are supported at the moment. 2527 // To keep the stack aligned according to platform abi the function 2528 // GetAlignedArgumentStackSize ensures that argument delta is always multiples 2529 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example) 2530 // If a tail called function callee has more arguments than the caller the 2531 // caller needs to make sure that there is room to move the RETADDR to. This is 2532 // achieved by reserving an area the size of the argument delta right after the 2533 // original REtADDR, but before the saved framepointer or the spilled registers 2534 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4) 2535 // stack layout: 2536 // arg1 2537 // arg2 2538 // RETADDR 2539 // [ new RETADDR 2540 // move area ] 2541 // (possible EBP) 2542 // ESI 2543 // EDI 2544 // local1 .. 2545 2546 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned 2547 /// for a 16 byte align requirement. 2548 unsigned 2549 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 2550 SelectionDAG& DAG) const { 2551 MachineFunction &MF = DAG.getMachineFunction(); 2552 const TargetMachine &TM = MF.getTarget(); 2553 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 2554 unsigned StackAlignment = TFI.getStackAlignment(); 2555 uint64_t AlignMask = StackAlignment - 1; 2556 int64_t Offset = StackSize; 2557 uint64_t SlotSize = TD->getPointerSize(); 2558 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) { 2559 // Number smaller than 12 so just add the difference. 2560 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask)); 2561 } else { 2562 // Mask out lower bits, add stackalignment once plus the 12 bytes. 2563 Offset = ((~AlignMask) & Offset) + StackAlignment + 2564 (StackAlignment-SlotSize); 2565 } 2566 return Offset; 2567 } 2568 2569 /// MatchingStackOffset - Return true if the given stack call argument is 2570 /// already available in the same position (relatively) of the caller's 2571 /// incoming argument stack. 2572 static 2573 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2574 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2575 const X86InstrInfo *TII) { 2576 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2577 int FI = INT_MAX; 2578 if (Arg.getOpcode() == ISD::CopyFromReg) { 2579 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2580 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2581 return false; 2582 MachineInstr *Def = MRI->getVRegDef(VR); 2583 if (!Def) 2584 return false; 2585 if (!Flags.isByVal()) { 2586 if (!TII->isLoadFromStackSlot(Def, FI)) 2587 return false; 2588 } else { 2589 unsigned Opcode = Def->getOpcode(); 2590 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) && 2591 Def->getOperand(1).isFI()) { 2592 FI = Def->getOperand(1).getIndex(); 2593 Bytes = Flags.getByValSize(); 2594 } else 2595 return false; 2596 } 2597 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2598 if (Flags.isByVal()) 2599 // ByVal argument is passed in as a pointer but it's now being 2600 // dereferenced. e.g. 2601 // define @foo(%struct.X* %A) { 2602 // tail call @bar(%struct.X* byval %A) 2603 // } 2604 return false; 2605 SDValue Ptr = Ld->getBasePtr(); 2606 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2607 if (!FINode) 2608 return false; 2609 FI = FINode->getIndex(); 2610 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) { 2611 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg); 2612 FI = FINode->getIndex(); 2613 Bytes = Flags.getByValSize(); 2614 } else 2615 return false; 2616 2617 assert(FI != INT_MAX); 2618 if (!MFI->isFixedObjectIndex(FI)) 2619 return false; 2620 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2621 } 2622 2623 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2624 /// for tail call optimization. Targets which want to do tail call 2625 /// optimization should implement this function. 2626 bool 2627 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2628 CallingConv::ID CalleeCC, 2629 bool isVarArg, 2630 bool isCalleeStructRet, 2631 bool isCallerStructRet, 2632 const SmallVectorImpl<ISD::OutputArg> &Outs, 2633 const SmallVectorImpl<SDValue> &OutVals, 2634 const SmallVectorImpl<ISD::InputArg> &Ins, 2635 SelectionDAG& DAG) const { 2636 if (!IsTailCallConvention(CalleeCC) && 2637 CalleeCC != CallingConv::C) 2638 return false; 2639 2640 // If -tailcallopt is specified, make fastcc functions tail-callable. 2641 const MachineFunction &MF = DAG.getMachineFunction(); 2642 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2643 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2644 bool CCMatch = CallerCC == CalleeCC; 2645 2646 if (GuaranteedTailCallOpt) { 2647 if (IsTailCallConvention(CalleeCC) && CCMatch) 2648 return true; 2649 return false; 2650 } 2651 2652 // Look for obvious safe cases to perform tail call optimization that do not 2653 // require ABI changes. This is what gcc calls sibcall. 2654 2655 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to 2656 // emit a special epilogue. 2657 if (RegInfo->needsStackRealignment(MF)) 2658 return false; 2659 2660 // Also avoid sibcall optimization if either caller or callee uses struct 2661 // return semantics. 2662 if (isCalleeStructRet || isCallerStructRet) 2663 return false; 2664 2665 // An stdcall caller is expected to clean up its arguments; the callee 2666 // isn't going to do that. 2667 if (!CCMatch && CallerCC==CallingConv::X86_StdCall) 2668 return false; 2669 2670 // Do not sibcall optimize vararg calls unless all arguments are passed via 2671 // registers. 2672 if (isVarArg && !Outs.empty()) { 2673 2674 // Optimizing for varargs on Win64 is unlikely to be safe without 2675 // additional testing. 2676 if (Subtarget->isTargetWin64()) 2677 return false; 2678 2679 SmallVector<CCValAssign, 16> ArgLocs; 2680 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2681 getTargetMachine(), ArgLocs, *DAG.getContext()); 2682 2683 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2684 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) 2685 if (!ArgLocs[i].isRegLoc()) 2686 return false; 2687 } 2688 2689 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack. 2690 // Therefore if it's not used by the call it is not safe to optimize this into 2691 // a sibcall. 2692 bool Unused = false; 2693 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 2694 if (!Ins[i].Used) { 2695 Unused = true; 2696 break; 2697 } 2698 } 2699 if (Unused) { 2700 SmallVector<CCValAssign, 16> RVLocs; 2701 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), 2702 getTargetMachine(), RVLocs, *DAG.getContext()); 2703 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 2704 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 2705 CCValAssign &VA = RVLocs[i]; 2706 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 2707 return false; 2708 } 2709 } 2710 2711 // If the calling conventions do not match, then we'd better make sure the 2712 // results are returned in the same way as what the caller expects. 2713 if (!CCMatch) { 2714 SmallVector<CCValAssign, 16> RVLocs1; 2715 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), 2716 getTargetMachine(), RVLocs1, *DAG.getContext()); 2717 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86); 2718 2719 SmallVector<CCValAssign, 16> RVLocs2; 2720 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), 2721 getTargetMachine(), RVLocs2, *DAG.getContext()); 2722 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86); 2723 2724 if (RVLocs1.size() != RVLocs2.size()) 2725 return false; 2726 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2727 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2728 return false; 2729 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2730 return false; 2731 if (RVLocs1[i].isRegLoc()) { 2732 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2733 return false; 2734 } else { 2735 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2736 return false; 2737 } 2738 } 2739 } 2740 2741 // If the callee takes no arguments then go on to check the results of the 2742 // call. 2743 if (!Outs.empty()) { 2744 // Check if stack adjustment is needed. For now, do not do this if any 2745 // argument is passed on the stack. 2746 SmallVector<CCValAssign, 16> ArgLocs; 2747 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2748 getTargetMachine(), ArgLocs, *DAG.getContext()); 2749 2750 // Allocate shadow area for Win64 2751 if (Subtarget->isTargetWin64()) { 2752 CCInfo.AllocateStack(32, 8); 2753 } 2754 2755 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2756 if (CCInfo.getNextStackOffset()) { 2757 MachineFunction &MF = DAG.getMachineFunction(); 2758 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) 2759 return false; 2760 2761 // Check if the arguments are already laid out in the right way as 2762 // the caller's fixed stack objects. 2763 MachineFrameInfo *MFI = MF.getFrameInfo(); 2764 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2765 const X86InstrInfo *TII = 2766 ((X86TargetMachine&)getTargetMachine()).getInstrInfo(); 2767 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2768 CCValAssign &VA = ArgLocs[i]; 2769 SDValue Arg = OutVals[i]; 2770 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2771 if (VA.getLocInfo() == CCValAssign::Indirect) 2772 return false; 2773 if (!VA.isRegLoc()) { 2774 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2775 MFI, MRI, TII)) 2776 return false; 2777 } 2778 } 2779 } 2780 2781 // If the tailcall address may be in a register, then make sure it's 2782 // possible to register allocate for it. In 32-bit, the call address can 2783 // only target EAX, EDX, or ECX since the tail call must be scheduled after 2784 // callee-saved registers are restored. These happen to be the same 2785 // registers used to pass 'inreg' arguments so watch out for those. 2786 if (!Subtarget->is64Bit() && 2787 !isa<GlobalAddressSDNode>(Callee) && 2788 !isa<ExternalSymbolSDNode>(Callee)) { 2789 unsigned NumInRegs = 0; 2790 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2791 CCValAssign &VA = ArgLocs[i]; 2792 if (!VA.isRegLoc()) 2793 continue; 2794 unsigned Reg = VA.getLocReg(); 2795 switch (Reg) { 2796 default: break; 2797 case X86::EAX: case X86::EDX: case X86::ECX: 2798 if (++NumInRegs == 3) 2799 return false; 2800 break; 2801 } 2802 } 2803 } 2804 } 2805 2806 return true; 2807 } 2808 2809 FastISel * 2810 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const { 2811 return X86::createFastISel(funcInfo); 2812 } 2813 2814 2815 //===----------------------------------------------------------------------===// 2816 // Other Lowering Hooks 2817 //===----------------------------------------------------------------------===// 2818 2819 static bool MayFoldLoad(SDValue Op) { 2820 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode()); 2821 } 2822 2823 static bool MayFoldIntoStore(SDValue Op) { 2824 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin()); 2825 } 2826 2827 static bool isTargetShuffle(unsigned Opcode) { 2828 switch(Opcode) { 2829 default: return false; 2830 case X86ISD::PSHUFD: 2831 case X86ISD::PSHUFHW: 2832 case X86ISD::PSHUFLW: 2833 case X86ISD::SHUFPD: 2834 case X86ISD::PALIGN: 2835 case X86ISD::SHUFPS: 2836 case X86ISD::MOVLHPS: 2837 case X86ISD::MOVLHPD: 2838 case X86ISD::MOVHLPS: 2839 case X86ISD::MOVLPS: 2840 case X86ISD::MOVLPD: 2841 case X86ISD::MOVSHDUP: 2842 case X86ISD::MOVSLDUP: 2843 case X86ISD::MOVDDUP: 2844 case X86ISD::MOVSS: 2845 case X86ISD::MOVSD: 2846 case X86ISD::UNPCKLPS: 2847 case X86ISD::UNPCKLPD: 2848 case X86ISD::VUNPCKLPSY: 2849 case X86ISD::VUNPCKLPDY: 2850 case X86ISD::PUNPCKLWD: 2851 case X86ISD::PUNPCKLBW: 2852 case X86ISD::PUNPCKLDQ: 2853 case X86ISD::PUNPCKLQDQ: 2854 case X86ISD::UNPCKHPS: 2855 case X86ISD::UNPCKHPD: 2856 case X86ISD::VUNPCKHPSY: 2857 case X86ISD::VUNPCKHPDY: 2858 case X86ISD::PUNPCKHWD: 2859 case X86ISD::PUNPCKHBW: 2860 case X86ISD::PUNPCKHDQ: 2861 case X86ISD::PUNPCKHQDQ: 2862 case X86ISD::VPERMILPS: 2863 case X86ISD::VPERMILPSY: 2864 case X86ISD::VPERMILPD: 2865 case X86ISD::VPERMILPDY: 2866 case X86ISD::VPERM2F128: 2867 return true; 2868 } 2869 return false; 2870 } 2871 2872 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2873 SDValue V1, SelectionDAG &DAG) { 2874 switch(Opc) { 2875 default: llvm_unreachable("Unknown x86 shuffle node"); 2876 case X86ISD::MOVSHDUP: 2877 case X86ISD::MOVSLDUP: 2878 case X86ISD::MOVDDUP: 2879 return DAG.getNode(Opc, dl, VT, V1); 2880 } 2881 2882 return SDValue(); 2883 } 2884 2885 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2886 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) { 2887 switch(Opc) { 2888 default: llvm_unreachable("Unknown x86 shuffle node"); 2889 case X86ISD::PSHUFD: 2890 case X86ISD::PSHUFHW: 2891 case X86ISD::PSHUFLW: 2892 case X86ISD::VPERMILPS: 2893 case X86ISD::VPERMILPSY: 2894 case X86ISD::VPERMILPD: 2895 case X86ISD::VPERMILPDY: 2896 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8)); 2897 } 2898 2899 return SDValue(); 2900 } 2901 2902 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2903 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) { 2904 switch(Opc) { 2905 default: llvm_unreachable("Unknown x86 shuffle node"); 2906 case X86ISD::PALIGN: 2907 case X86ISD::SHUFPD: 2908 case X86ISD::SHUFPS: 2909 case X86ISD::VPERM2F128: 2910 return DAG.getNode(Opc, dl, VT, V1, V2, 2911 DAG.getConstant(TargetMask, MVT::i8)); 2912 } 2913 return SDValue(); 2914 } 2915 2916 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2917 SDValue V1, SDValue V2, SelectionDAG &DAG) { 2918 switch(Opc) { 2919 default: llvm_unreachable("Unknown x86 shuffle node"); 2920 case X86ISD::MOVLHPS: 2921 case X86ISD::MOVLHPD: 2922 case X86ISD::MOVHLPS: 2923 case X86ISD::MOVLPS: 2924 case X86ISD::MOVLPD: 2925 case X86ISD::MOVSS: 2926 case X86ISD::MOVSD: 2927 case X86ISD::UNPCKLPS: 2928 case X86ISD::UNPCKLPD: 2929 case X86ISD::VUNPCKLPSY: 2930 case X86ISD::VUNPCKLPDY: 2931 case X86ISD::PUNPCKLWD: 2932 case X86ISD::PUNPCKLBW: 2933 case X86ISD::PUNPCKLDQ: 2934 case X86ISD::PUNPCKLQDQ: 2935 case X86ISD::UNPCKHPS: 2936 case X86ISD::UNPCKHPD: 2937 case X86ISD::VUNPCKHPSY: 2938 case X86ISD::VUNPCKHPDY: 2939 case X86ISD::PUNPCKHWD: 2940 case X86ISD::PUNPCKHBW: 2941 case X86ISD::PUNPCKHDQ: 2942 case X86ISD::PUNPCKHQDQ: 2943 return DAG.getNode(Opc, dl, VT, V1, V2); 2944 } 2945 return SDValue(); 2946 } 2947 2948 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { 2949 MachineFunction &MF = DAG.getMachineFunction(); 2950 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2951 int ReturnAddrIndex = FuncInfo->getRAIndex(); 2952 2953 if (ReturnAddrIndex == 0) { 2954 // Set up a frame object for the return address. 2955 uint64_t SlotSize = TD->getPointerSize(); 2956 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize, 2957 false); 2958 FuncInfo->setRAIndex(ReturnAddrIndex); 2959 } 2960 2961 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); 2962 } 2963 2964 2965 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, 2966 bool hasSymbolicDisplacement) { 2967 // Offset should fit into 32 bit immediate field. 2968 if (!isInt<32>(Offset)) 2969 return false; 2970 2971 // If we don't have a symbolic displacement - we don't have any extra 2972 // restrictions. 2973 if (!hasSymbolicDisplacement) 2974 return true; 2975 2976 // FIXME: Some tweaks might be needed for medium code model. 2977 if (M != CodeModel::Small && M != CodeModel::Kernel) 2978 return false; 2979 2980 // For small code model we assume that latest object is 16MB before end of 31 2981 // bits boundary. We may also accept pretty large negative constants knowing 2982 // that all objects are in the positive half of address space. 2983 if (M == CodeModel::Small && Offset < 16*1024*1024) 2984 return true; 2985 2986 // For kernel code model we know that all object resist in the negative half 2987 // of 32bits address space. We may not accept negative offsets, since they may 2988 // be just off and we may accept pretty large positive ones. 2989 if (M == CodeModel::Kernel && Offset > 0) 2990 return true; 2991 2992 return false; 2993 } 2994 2995 /// isCalleePop - Determines whether the callee is required to pop its 2996 /// own arguments. Callee pop is necessary to support tail calls. 2997 bool X86::isCalleePop(CallingConv::ID CallingConv, 2998 bool is64Bit, bool IsVarArg, bool TailCallOpt) { 2999 if (IsVarArg) 3000 return false; 3001 3002 switch (CallingConv) { 3003 default: 3004 return false; 3005 case CallingConv::X86_StdCall: 3006 return !is64Bit; 3007 case CallingConv::X86_FastCall: 3008 return !is64Bit; 3009 case CallingConv::X86_ThisCall: 3010 return !is64Bit; 3011 case CallingConv::Fast: 3012 return TailCallOpt; 3013 case CallingConv::GHC: 3014 return TailCallOpt; 3015 } 3016 } 3017 3018 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86 3019 /// specific condition code, returning the condition code and the LHS/RHS of the 3020 /// comparison to make. 3021 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP, 3022 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) { 3023 if (!isFP) { 3024 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 3025 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) { 3026 // X > -1 -> X == 0, jump !sign. 3027 RHS = DAG.getConstant(0, RHS.getValueType()); 3028 return X86::COND_NS; 3029 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) { 3030 // X < 0 -> X == 0, jump on sign. 3031 return X86::COND_S; 3032 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) { 3033 // X < 1 -> X <= 0 3034 RHS = DAG.getConstant(0, RHS.getValueType()); 3035 return X86::COND_LE; 3036 } 3037 } 3038 3039 switch (SetCCOpcode) { 3040 default: llvm_unreachable("Invalid integer condition!"); 3041 case ISD::SETEQ: return X86::COND_E; 3042 case ISD::SETGT: return X86::COND_G; 3043 case ISD::SETGE: return X86::COND_GE; 3044 case ISD::SETLT: return X86::COND_L; 3045 case ISD::SETLE: return X86::COND_LE; 3046 case ISD::SETNE: return X86::COND_NE; 3047 case ISD::SETULT: return X86::COND_B; 3048 case ISD::SETUGT: return X86::COND_A; 3049 case ISD::SETULE: return X86::COND_BE; 3050 case ISD::SETUGE: return X86::COND_AE; 3051 } 3052 } 3053 3054 // First determine if it is required or is profitable to flip the operands. 3055 3056 // If LHS is a foldable load, but RHS is not, flip the condition. 3057 if (ISD::isNON_EXTLoad(LHS.getNode()) && 3058 !ISD::isNON_EXTLoad(RHS.getNode())) { 3059 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode); 3060 std::swap(LHS, RHS); 3061 } 3062 3063 switch (SetCCOpcode) { 3064 default: break; 3065 case ISD::SETOLT: 3066 case ISD::SETOLE: 3067 case ISD::SETUGT: 3068 case ISD::SETUGE: 3069 std::swap(LHS, RHS); 3070 break; 3071 } 3072 3073 // On a floating point condition, the flags are set as follows: 3074 // ZF PF CF op 3075 // 0 | 0 | 0 | X > Y 3076 // 0 | 0 | 1 | X < Y 3077 // 1 | 0 | 0 | X == Y 3078 // 1 | 1 | 1 | unordered 3079 switch (SetCCOpcode) { 3080 default: llvm_unreachable("Condcode should be pre-legalized away"); 3081 case ISD::SETUEQ: 3082 case ISD::SETEQ: return X86::COND_E; 3083 case ISD::SETOLT: // flipped 3084 case ISD::SETOGT: 3085 case ISD::SETGT: return X86::COND_A; 3086 case ISD::SETOLE: // flipped 3087 case ISD::SETOGE: 3088 case ISD::SETGE: return X86::COND_AE; 3089 case ISD::SETUGT: // flipped 3090 case ISD::SETULT: 3091 case ISD::SETLT: return X86::COND_B; 3092 case ISD::SETUGE: // flipped 3093 case ISD::SETULE: 3094 case ISD::SETLE: return X86::COND_BE; 3095 case ISD::SETONE: 3096 case ISD::SETNE: return X86::COND_NE; 3097 case ISD::SETUO: return X86::COND_P; 3098 case ISD::SETO: return X86::COND_NP; 3099 case ISD::SETOEQ: 3100 case ISD::SETUNE: return X86::COND_INVALID; 3101 } 3102 } 3103 3104 /// hasFPCMov - is there a floating point cmov for the specific X86 condition 3105 /// code. Current x86 isa includes the following FP cmov instructions: 3106 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu. 3107 static bool hasFPCMov(unsigned X86CC) { 3108 switch (X86CC) { 3109 default: 3110 return false; 3111 case X86::COND_B: 3112 case X86::COND_BE: 3113 case X86::COND_E: 3114 case X86::COND_P: 3115 case X86::COND_A: 3116 case X86::COND_AE: 3117 case X86::COND_NE: 3118 case X86::COND_NP: 3119 return true; 3120 } 3121 } 3122 3123 /// isFPImmLegal - Returns true if the target can instruction select the 3124 /// specified FP immediate natively. If false, the legalizer will 3125 /// materialize the FP immediate as a load from a constant pool. 3126 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 3127 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) { 3128 if (Imm.bitwiseIsEqual(LegalFPImmediates[i])) 3129 return true; 3130 } 3131 return false; 3132 } 3133 3134 /// isUndefOrInRange - Return true if Val is undef or if its value falls within 3135 /// the specified range (L, H]. 3136 static bool isUndefOrInRange(int Val, int Low, int Hi) { 3137 return (Val < 0) || (Val >= Low && Val < Hi); 3138 } 3139 3140 /// isUndefOrInRange - Return true if every element in Mask, begining 3141 /// from position Pos and ending in Pos+Size, falls within the specified 3142 /// range (L, L+Pos]. or is undef. 3143 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask, 3144 int Pos, int Size, int Low, int Hi) { 3145 for (int i = Pos, e = Pos+Size; i != e; ++i) 3146 if (!isUndefOrInRange(Mask[i], Low, Hi)) 3147 return false; 3148 return true; 3149 } 3150 3151 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the 3152 /// specified value. 3153 static bool isUndefOrEqual(int Val, int CmpVal) { 3154 if (Val < 0 || Val == CmpVal) 3155 return true; 3156 return false; 3157 } 3158 3159 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining 3160 /// from position Pos and ending in Pos+Size, falls within the specified 3161 /// sequential range (L, L+Pos]. or is undef. 3162 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask, 3163 int Pos, int Size, int Low) { 3164 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low) 3165 if (!isUndefOrEqual(Mask[i], Low)) 3166 return false; 3167 return true; 3168 } 3169 3170 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that 3171 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference 3172 /// the second operand. 3173 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3174 if (VT == MVT::v4f32 || VT == MVT::v4i32 ) 3175 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4); 3176 if (VT == MVT::v2f64 || VT == MVT::v2i64) 3177 return (Mask[0] < 2 && Mask[1] < 2); 3178 return false; 3179 } 3180 3181 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) { 3182 SmallVector<int, 8> M; 3183 N->getMask(M); 3184 return ::isPSHUFDMask(M, N->getValueType(0)); 3185 } 3186 3187 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that 3188 /// is suitable for input to PSHUFHW. 3189 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3190 if (VT != MVT::v8i16) 3191 return false; 3192 3193 // Lower quadword copied in order or undef. 3194 for (int i = 0; i != 4; ++i) 3195 if (Mask[i] >= 0 && Mask[i] != i) 3196 return false; 3197 3198 // Upper quadword shuffled. 3199 for (int i = 4; i != 8; ++i) 3200 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7)) 3201 return false; 3202 3203 return true; 3204 } 3205 3206 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) { 3207 SmallVector<int, 8> M; 3208 N->getMask(M); 3209 return ::isPSHUFHWMask(M, N->getValueType(0)); 3210 } 3211 3212 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that 3213 /// is suitable for input to PSHUFLW. 3214 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3215 if (VT != MVT::v8i16) 3216 return false; 3217 3218 // Upper quadword copied in order. 3219 for (int i = 4; i != 8; ++i) 3220 if (Mask[i] >= 0 && Mask[i] != i) 3221 return false; 3222 3223 // Lower quadword shuffled. 3224 for (int i = 0; i != 4; ++i) 3225 if (Mask[i] >= 4) 3226 return false; 3227 3228 return true; 3229 } 3230 3231 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) { 3232 SmallVector<int, 8> M; 3233 N->getMask(M); 3234 return ::isPSHUFLWMask(M, N->getValueType(0)); 3235 } 3236 3237 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that 3238 /// is suitable for input to PALIGNR. 3239 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT, 3240 bool hasSSSE3OrAVX) { 3241 int i, e = VT.getVectorNumElements(); 3242 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64) 3243 return false; 3244 3245 // Do not handle v2i64 / v2f64 shuffles with palignr. 3246 if (e < 4 || !hasSSSE3OrAVX) 3247 return false; 3248 3249 for (i = 0; i != e; ++i) 3250 if (Mask[i] >= 0) 3251 break; 3252 3253 // All undef, not a palignr. 3254 if (i == e) 3255 return false; 3256 3257 // Make sure we're shifting in the right direction. 3258 if (Mask[i] <= i) 3259 return false; 3260 3261 int s = Mask[i] - i; 3262 3263 // Check the rest of the elements to see if they are consecutive. 3264 for (++i; i != e; ++i) { 3265 int m = Mask[i]; 3266 if (m >= 0 && m != s+i) 3267 return false; 3268 } 3269 return true; 3270 } 3271 3272 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand 3273 /// specifies a shuffle of elements that is suitable for input to 256-bit 3274 /// VSHUFPSY. 3275 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT, 3276 const X86Subtarget *Subtarget) { 3277 int NumElems = VT.getVectorNumElements(); 3278 3279 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256) 3280 return false; 3281 3282 if (NumElems != 8) 3283 return false; 3284 3285 // VSHUFPSY divides the resulting vector into 4 chunks. 3286 // The sources are also splitted into 4 chunks, and each destination 3287 // chunk must come from a different source chunk. 3288 // 3289 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0 3290 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9 3291 // 3292 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4, 3293 // Y3..Y0, Y3..Y0, X3..X0, X3..X0 3294 // 3295 int QuarterSize = NumElems/4; 3296 int HalfSize = QuarterSize*2; 3297 for (int i = 0; i < QuarterSize; ++i) 3298 if (!isUndefOrInRange(Mask[i], 0, HalfSize)) 3299 return false; 3300 for (int i = QuarterSize; i < QuarterSize*2; ++i) 3301 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize)) 3302 return false; 3303 3304 // The mask of the second half must be the same as the first but with 3305 // the appropriate offsets. This works in the same way as VPERMILPS 3306 // works with masks. 3307 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) { 3308 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems)) 3309 return false; 3310 int FstHalfIdx = i-HalfSize; 3311 if (Mask[FstHalfIdx] < 0) 3312 continue; 3313 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize)) 3314 return false; 3315 } 3316 for (int i = QuarterSize*3; i < NumElems; ++i) { 3317 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2)) 3318 return false; 3319 int FstHalfIdx = i-HalfSize; 3320 if (Mask[FstHalfIdx] < 0) 3321 continue; 3322 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize)) 3323 return false; 3324 3325 } 3326 3327 return true; 3328 } 3329 3330 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle 3331 /// the specified VECTOR_MASK mask with VSHUFPSY instruction. 3332 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) { 3333 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3334 EVT VT = SVOp->getValueType(0); 3335 int NumElems = VT.getVectorNumElements(); 3336 3337 assert(NumElems == 8 && VT.getSizeInBits() == 256 && 3338 "Only supports v8i32 and v8f32 types"); 3339 3340 int HalfSize = NumElems/2; 3341 unsigned Mask = 0; 3342 for (int i = 0; i != NumElems ; ++i) { 3343 if (SVOp->getMaskElt(i) < 0) 3344 continue; 3345 // The mask of the first half must be equal to the second one. 3346 unsigned Shamt = (i%HalfSize)*2; 3347 unsigned Elt = SVOp->getMaskElt(i) % HalfSize; 3348 Mask |= Elt << Shamt; 3349 } 3350 3351 return Mask; 3352 } 3353 3354 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand 3355 /// specifies a shuffle of elements that is suitable for input to 256-bit 3356 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS 3357 /// version and the mask of the second half isn't binded with the first 3358 /// one. 3359 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT, 3360 const X86Subtarget *Subtarget) { 3361 int NumElems = VT.getVectorNumElements(); 3362 3363 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256) 3364 return false; 3365 3366 if (NumElems != 4) 3367 return false; 3368 3369 // VSHUFPSY divides the resulting vector into 4 chunks. 3370 // The sources are also splitted into 4 chunks, and each destination 3371 // chunk must come from a different source chunk. 3372 // 3373 // SRC1 => X3 X2 X1 X0 3374 // SRC2 => Y3 Y2 Y1 Y0 3375 // 3376 // DST => Y2..Y3, X2..X3, Y1..Y0, X1..X0 3377 // 3378 int QuarterSize = NumElems/4; 3379 int HalfSize = QuarterSize*2; 3380 for (int i = 0; i < QuarterSize; ++i) 3381 if (!isUndefOrInRange(Mask[i], 0, HalfSize)) 3382 return false; 3383 for (int i = QuarterSize; i < QuarterSize*2; ++i) 3384 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize)) 3385 return false; 3386 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) 3387 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems)) 3388 return false; 3389 for (int i = QuarterSize*3; i < NumElems; ++i) 3390 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2)) 3391 return false; 3392 3393 return true; 3394 } 3395 3396 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle 3397 /// the specified VECTOR_MASK mask with VSHUFPDY instruction. 3398 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) { 3399 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3400 EVT VT = SVOp->getValueType(0); 3401 int NumElems = VT.getVectorNumElements(); 3402 3403 assert(NumElems == 4 && VT.getSizeInBits() == 256 && 3404 "Only supports v4i64 and v4f64 types"); 3405 3406 int HalfSize = NumElems/2; 3407 unsigned Mask = 0; 3408 for (int i = 0; i != NumElems ; ++i) { 3409 if (SVOp->getMaskElt(i) < 0) 3410 continue; 3411 int Elt = SVOp->getMaskElt(i) % HalfSize; 3412 Mask |= Elt << i; 3413 } 3414 3415 return Mask; 3416 } 3417 3418 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand 3419 /// specifies a shuffle of elements that is suitable for input to 128-bit 3420 /// SHUFPS and SHUFPD. 3421 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3422 int NumElems = VT.getVectorNumElements(); 3423 3424 if (VT.getSizeInBits() != 128) 3425 return false; 3426 3427 if (NumElems != 2 && NumElems != 4) 3428 return false; 3429 3430 int Half = NumElems / 2; 3431 for (int i = 0; i < Half; ++i) 3432 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3433 return false; 3434 for (int i = Half; i < NumElems; ++i) 3435 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3436 return false; 3437 3438 return true; 3439 } 3440 3441 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) { 3442 SmallVector<int, 8> M; 3443 N->getMask(M); 3444 return ::isSHUFPMask(M, N->getValueType(0)); 3445 } 3446 3447 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly 3448 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower 3449 /// half elements to come from vector 1 (which would equal the dest.) and 3450 /// the upper half to come from vector 2. 3451 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3452 int NumElems = VT.getVectorNumElements(); 3453 3454 if (NumElems != 2 && NumElems != 4) 3455 return false; 3456 3457 int Half = NumElems / 2; 3458 for (int i = 0; i < Half; ++i) 3459 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3460 return false; 3461 for (int i = Half; i < NumElems; ++i) 3462 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3463 return false; 3464 return true; 3465 } 3466 3467 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) { 3468 SmallVector<int, 8> M; 3469 N->getMask(M); 3470 return isCommutedSHUFPMask(M, N->getValueType(0)); 3471 } 3472 3473 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand 3474 /// specifies a shuffle of elements that is suitable for input to MOVHLPS. 3475 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) { 3476 EVT VT = N->getValueType(0); 3477 unsigned NumElems = VT.getVectorNumElements(); 3478 3479 if (VT.getSizeInBits() != 128) 3480 return false; 3481 3482 if (NumElems != 4) 3483 return false; 3484 3485 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3 3486 return isUndefOrEqual(N->getMaskElt(0), 6) && 3487 isUndefOrEqual(N->getMaskElt(1), 7) && 3488 isUndefOrEqual(N->getMaskElt(2), 2) && 3489 isUndefOrEqual(N->getMaskElt(3), 3); 3490 } 3491 3492 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form 3493 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef, 3494 /// <2, 3, 2, 3> 3495 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) { 3496 EVT VT = N->getValueType(0); 3497 unsigned NumElems = VT.getVectorNumElements(); 3498 3499 if (VT.getSizeInBits() != 128) 3500 return false; 3501 3502 if (NumElems != 4) 3503 return false; 3504 3505 return isUndefOrEqual(N->getMaskElt(0), 2) && 3506 isUndefOrEqual(N->getMaskElt(1), 3) && 3507 isUndefOrEqual(N->getMaskElt(2), 2) && 3508 isUndefOrEqual(N->getMaskElt(3), 3); 3509 } 3510 3511 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand 3512 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}. 3513 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) { 3514 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3515 3516 if (NumElems != 2 && NumElems != 4) 3517 return false; 3518 3519 for (unsigned i = 0; i < NumElems/2; ++i) 3520 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems)) 3521 return false; 3522 3523 for (unsigned i = NumElems/2; i < NumElems; ++i) 3524 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3525 return false; 3526 3527 return true; 3528 } 3529 3530 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand 3531 /// specifies a shuffle of elements that is suitable for input to MOVLHPS. 3532 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) { 3533 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3534 3535 if ((NumElems != 2 && NumElems != 4) 3536 || N->getValueType(0).getSizeInBits() > 128) 3537 return false; 3538 3539 for (unsigned i = 0; i < NumElems/2; ++i) 3540 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3541 return false; 3542 3543 for (unsigned i = 0; i < NumElems/2; ++i) 3544 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems)) 3545 return false; 3546 3547 return true; 3548 } 3549 3550 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand 3551 /// specifies a shuffle of elements that is suitable for input to UNPCKL. 3552 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3553 bool V2IsSplat = false) { 3554 int NumElts = VT.getVectorNumElements(); 3555 3556 assert((VT.is128BitVector() || VT.is256BitVector()) && 3557 "Unsupported vector type for unpckh"); 3558 3559 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8) 3560 return false; 3561 3562 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3563 // independently on 128-bit lanes. 3564 unsigned NumLanes = VT.getSizeInBits()/128; 3565 unsigned NumLaneElts = NumElts/NumLanes; 3566 3567 unsigned Start = 0; 3568 unsigned End = NumLaneElts; 3569 for (unsigned s = 0; s < NumLanes; ++s) { 3570 for (unsigned i = Start, j = s * NumLaneElts; 3571 i != End; 3572 i += 2, ++j) { 3573 int BitI = Mask[i]; 3574 int BitI1 = Mask[i+1]; 3575 if (!isUndefOrEqual(BitI, j)) 3576 return false; 3577 if (V2IsSplat) { 3578 if (!isUndefOrEqual(BitI1, NumElts)) 3579 return false; 3580 } else { 3581 if (!isUndefOrEqual(BitI1, j + NumElts)) 3582 return false; 3583 } 3584 } 3585 // Process the next 128 bits. 3586 Start += NumLaneElts; 3587 End += NumLaneElts; 3588 } 3589 3590 return true; 3591 } 3592 3593 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) { 3594 SmallVector<int, 8> M; 3595 N->getMask(M); 3596 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat); 3597 } 3598 3599 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand 3600 /// specifies a shuffle of elements that is suitable for input to UNPCKH. 3601 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT, 3602 bool V2IsSplat = false) { 3603 int NumElts = VT.getVectorNumElements(); 3604 3605 assert((VT.is128BitVector() || VT.is256BitVector()) && 3606 "Unsupported vector type for unpckh"); 3607 3608 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8) 3609 return false; 3610 3611 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3612 // independently on 128-bit lanes. 3613 unsigned NumLanes = VT.getSizeInBits()/128; 3614 unsigned NumLaneElts = NumElts/NumLanes; 3615 3616 unsigned Start = 0; 3617 unsigned End = NumLaneElts; 3618 for (unsigned l = 0; l != NumLanes; ++l) { 3619 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2; 3620 i != End; i += 2, ++j) { 3621 int BitI = Mask[i]; 3622 int BitI1 = Mask[i+1]; 3623 if (!isUndefOrEqual(BitI, j)) 3624 return false; 3625 if (V2IsSplat) { 3626 if (isUndefOrEqual(BitI1, NumElts)) 3627 return false; 3628 } else { 3629 if (!isUndefOrEqual(BitI1, j+NumElts)) 3630 return false; 3631 } 3632 } 3633 // Process the next 128 bits. 3634 Start += NumLaneElts; 3635 End += NumLaneElts; 3636 } 3637 return true; 3638 } 3639 3640 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) { 3641 SmallVector<int, 8> M; 3642 N->getMask(M); 3643 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat); 3644 } 3645 3646 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form 3647 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef, 3648 /// <0, 0, 1, 1> 3649 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3650 int NumElems = VT.getVectorNumElements(); 3651 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3652 return false; 3653 3654 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern 3655 // FIXME: Need a better way to get rid of this, there's no latency difference 3656 // between UNPCKLPD and MOVDDUP, the later should always be checked first and 3657 // the former later. We should also remove the "_undef" special mask. 3658 if (NumElems == 4 && VT.getSizeInBits() == 256) 3659 return false; 3660 3661 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3662 // independently on 128-bit lanes. 3663 unsigned NumLanes = VT.getSizeInBits() / 128; 3664 unsigned NumLaneElts = NumElems / NumLanes; 3665 3666 for (unsigned s = 0; s < NumLanes; ++s) { 3667 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts; 3668 i != NumLaneElts * (s + 1); 3669 i += 2, ++j) { 3670 int BitI = Mask[i]; 3671 int BitI1 = Mask[i+1]; 3672 3673 if (!isUndefOrEqual(BitI, j)) 3674 return false; 3675 if (!isUndefOrEqual(BitI1, j)) 3676 return false; 3677 } 3678 } 3679 3680 return true; 3681 } 3682 3683 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) { 3684 SmallVector<int, 8> M; 3685 N->getMask(M); 3686 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0)); 3687 } 3688 3689 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form 3690 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef, 3691 /// <2, 2, 3, 3> 3692 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3693 int NumElems = VT.getVectorNumElements(); 3694 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3695 return false; 3696 3697 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) { 3698 int BitI = Mask[i]; 3699 int BitI1 = Mask[i+1]; 3700 if (!isUndefOrEqual(BitI, j)) 3701 return false; 3702 if (!isUndefOrEqual(BitI1, j)) 3703 return false; 3704 } 3705 return true; 3706 } 3707 3708 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) { 3709 SmallVector<int, 8> M; 3710 N->getMask(M); 3711 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0)); 3712 } 3713 3714 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand 3715 /// specifies a shuffle of elements that is suitable for input to MOVSS, 3716 /// MOVSD, and MOVD, i.e. setting the lowest element. 3717 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3718 if (VT.getVectorElementType().getSizeInBits() < 32) 3719 return false; 3720 3721 int NumElts = VT.getVectorNumElements(); 3722 3723 if (!isUndefOrEqual(Mask[0], NumElts)) 3724 return false; 3725 3726 for (int i = 1; i < NumElts; ++i) 3727 if (!isUndefOrEqual(Mask[i], i)) 3728 return false; 3729 3730 return true; 3731 } 3732 3733 bool X86::isMOVLMask(ShuffleVectorSDNode *N) { 3734 SmallVector<int, 8> M; 3735 N->getMask(M); 3736 return ::isMOVLMask(M, N->getValueType(0)); 3737 } 3738 3739 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered 3740 /// as permutations between 128-bit chunks or halves. As an example: this 3741 /// shuffle bellow: 3742 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15> 3743 /// The first half comes from the second half of V1 and the second half from the 3744 /// the second half of V2. 3745 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT, 3746 const X86Subtarget *Subtarget) { 3747 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256) 3748 return false; 3749 3750 // The shuffle result is divided into half A and half B. In total the two 3751 // sources have 4 halves, namely: C, D, E, F. The final values of A and 3752 // B must come from C, D, E or F. 3753 int HalfSize = VT.getVectorNumElements()/2; 3754 bool MatchA = false, MatchB = false; 3755 3756 // Check if A comes from one of C, D, E, F. 3757 for (int Half = 0; Half < 4; ++Half) { 3758 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) { 3759 MatchA = true; 3760 break; 3761 } 3762 } 3763 3764 // Check if B comes from one of C, D, E, F. 3765 for (int Half = 0; Half < 4; ++Half) { 3766 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) { 3767 MatchB = true; 3768 break; 3769 } 3770 } 3771 3772 return MatchA && MatchB; 3773 } 3774 3775 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle 3776 /// the specified VECTOR_MASK mask with VPERM2F128 instructions. 3777 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) { 3778 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3779 EVT VT = SVOp->getValueType(0); 3780 3781 int HalfSize = VT.getVectorNumElements()/2; 3782 3783 int FstHalf = 0, SndHalf = 0; 3784 for (int i = 0; i < HalfSize; ++i) { 3785 if (SVOp->getMaskElt(i) > 0) { 3786 FstHalf = SVOp->getMaskElt(i)/HalfSize; 3787 break; 3788 } 3789 } 3790 for (int i = HalfSize; i < HalfSize*2; ++i) { 3791 if (SVOp->getMaskElt(i) > 0) { 3792 SndHalf = SVOp->getMaskElt(i)/HalfSize; 3793 break; 3794 } 3795 } 3796 3797 return (FstHalf | (SndHalf << 4)); 3798 } 3799 3800 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand 3801 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*. 3802 /// Note that VPERMIL mask matching is different depending whether theunderlying 3803 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point 3804 /// to the same elements of the low, but to the higher half of the source. 3805 /// In VPERMILPD the two lanes could be shuffled independently of each other 3806 /// with the same restriction that lanes can't be crossed. 3807 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT, 3808 const X86Subtarget *Subtarget) { 3809 int NumElts = VT.getVectorNumElements(); 3810 int NumLanes = VT.getSizeInBits()/128; 3811 3812 if (!Subtarget->hasAVX()) 3813 return false; 3814 3815 // Only match 256-bit with 64-bit types 3816 if (VT.getSizeInBits() != 256 || NumElts != 4) 3817 return false; 3818 3819 // The mask on the high lane is independent of the low. Both can match 3820 // any element in inside its own lane, but can't cross. 3821 int LaneSize = NumElts/NumLanes; 3822 for (int l = 0; l < NumLanes; ++l) 3823 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) { 3824 int LaneStart = l*LaneSize; 3825 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize)) 3826 return false; 3827 } 3828 3829 return true; 3830 } 3831 3832 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand 3833 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*. 3834 /// Note that VPERMIL mask matching is different depending whether theunderlying 3835 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point 3836 /// to the same elements of the low, but to the higher half of the source. 3837 /// In VPERMILPD the two lanes could be shuffled independently of each other 3838 /// with the same restriction that lanes can't be crossed. 3839 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT, 3840 const X86Subtarget *Subtarget) { 3841 unsigned NumElts = VT.getVectorNumElements(); 3842 unsigned NumLanes = VT.getSizeInBits()/128; 3843 3844 if (!Subtarget->hasAVX()) 3845 return false; 3846 3847 // Only match 256-bit with 32-bit types 3848 if (VT.getSizeInBits() != 256 || NumElts != 8) 3849 return false; 3850 3851 // The mask on the high lane should be the same as the low. Actually, 3852 // they can differ if any of the corresponding index in a lane is undef 3853 // and the other stays in range. 3854 int LaneSize = NumElts/NumLanes; 3855 for (int i = 0; i < LaneSize; ++i) { 3856 int HighElt = i+LaneSize; 3857 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts); 3858 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize); 3859 3860 if (!HighValid || !LowValid) 3861 return false; 3862 if (Mask[i] < 0 || Mask[HighElt] < 0) 3863 continue; 3864 if (Mask[HighElt]-Mask[i] != LaneSize) 3865 return false; 3866 } 3867 3868 return true; 3869 } 3870 3871 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle 3872 /// the specified VECTOR_MASK mask with VPERMILPS* instructions. 3873 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) { 3874 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3875 EVT VT = SVOp->getValueType(0); 3876 3877 int NumElts = VT.getVectorNumElements(); 3878 int NumLanes = VT.getSizeInBits()/128; 3879 int LaneSize = NumElts/NumLanes; 3880 3881 // Although the mask is equal for both lanes do it twice to get the cases 3882 // where a mask will match because the same mask element is undef on the 3883 // first half but valid on the second. This would get pathological cases 3884 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid. 3885 unsigned Mask = 0; 3886 for (int l = 0; l < NumLanes; ++l) { 3887 for (int i = 0; i < LaneSize; ++i) { 3888 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize)); 3889 if (MaskElt < 0) 3890 continue; 3891 if (MaskElt >= LaneSize) 3892 MaskElt -= LaneSize; 3893 Mask |= MaskElt << (i*2); 3894 } 3895 } 3896 3897 return Mask; 3898 } 3899 3900 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle 3901 /// the specified VECTOR_MASK mask with VPERMILPD* instructions. 3902 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) { 3903 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3904 EVT VT = SVOp->getValueType(0); 3905 3906 int NumElts = VT.getVectorNumElements(); 3907 int NumLanes = VT.getSizeInBits()/128; 3908 3909 unsigned Mask = 0; 3910 int LaneSize = NumElts/NumLanes; 3911 for (int l = 0; l < NumLanes; ++l) 3912 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) { 3913 int MaskElt = SVOp->getMaskElt(i); 3914 if (MaskElt < 0) 3915 continue; 3916 Mask |= (MaskElt-l*LaneSize) << i; 3917 } 3918 3919 return Mask; 3920 } 3921 3922 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse 3923 /// of what x86 movss want. X86 movs requires the lowest element to be lowest 3924 /// element of vector 2 and the other elements to come from vector 1 in order. 3925 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3926 bool V2IsSplat = false, bool V2IsUndef = false) { 3927 int NumOps = VT.getVectorNumElements(); 3928 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16) 3929 return false; 3930 3931 if (!isUndefOrEqual(Mask[0], 0)) 3932 return false; 3933 3934 for (int i = 1; i < NumOps; ++i) 3935 if (!(isUndefOrEqual(Mask[i], i+NumOps) || 3936 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) || 3937 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps)))) 3938 return false; 3939 3940 return true; 3941 } 3942 3943 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false, 3944 bool V2IsUndef = false) { 3945 SmallVector<int, 8> M; 3946 N->getMask(M); 3947 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef); 3948 } 3949 3950 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3951 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP. 3952 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7> 3953 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N, 3954 const X86Subtarget *Subtarget) { 3955 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX()) 3956 return false; 3957 3958 // The second vector must be undef 3959 if (N->getOperand(1).getOpcode() != ISD::UNDEF) 3960 return false; 3961 3962 EVT VT = N->getValueType(0); 3963 unsigned NumElems = VT.getVectorNumElements(); 3964 3965 if ((VT.getSizeInBits() == 128 && NumElems != 4) || 3966 (VT.getSizeInBits() == 256 && NumElems != 8)) 3967 return false; 3968 3969 // "i+1" is the value the indexed mask element must have 3970 for (unsigned i = 0; i < NumElems; i += 2) 3971 if (!isUndefOrEqual(N->getMaskElt(i), i+1) || 3972 !isUndefOrEqual(N->getMaskElt(i+1), i+1)) 3973 return false; 3974 3975 return true; 3976 } 3977 3978 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3979 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP. 3980 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6> 3981 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N, 3982 const X86Subtarget *Subtarget) { 3983 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX()) 3984 return false; 3985 3986 // The second vector must be undef 3987 if (N->getOperand(1).getOpcode() != ISD::UNDEF) 3988 return false; 3989 3990 EVT VT = N->getValueType(0); 3991 unsigned NumElems = VT.getVectorNumElements(); 3992 3993 if ((VT.getSizeInBits() == 128 && NumElems != 4) || 3994 (VT.getSizeInBits() == 256 && NumElems != 8)) 3995 return false; 3996 3997 // "i" is the value the indexed mask element must have 3998 for (unsigned i = 0; i < NumElems; i += 2) 3999 if (!isUndefOrEqual(N->getMaskElt(i), i) || 4000 !isUndefOrEqual(N->getMaskElt(i+1), i)) 4001 return false; 4002 4003 return true; 4004 } 4005 4006 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand 4007 /// specifies a shuffle of elements that is suitable for input to 256-bit 4008 /// version of MOVDDUP. 4009 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N, 4010 const X86Subtarget *Subtarget) { 4011 EVT VT = N->getValueType(0); 4012 int NumElts = VT.getVectorNumElements(); 4013 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF; 4014 4015 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 || 4016 !V2IsUndef || NumElts != 4) 4017 return false; 4018 4019 for (int i = 0; i != NumElts/2; ++i) 4020 if (!isUndefOrEqual(N->getMaskElt(i), 0)) 4021 return false; 4022 for (int i = NumElts/2; i != NumElts; ++i) 4023 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2)) 4024 return false; 4025 return true; 4026 } 4027 4028 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand 4029 /// specifies a shuffle of elements that is suitable for input to 128-bit 4030 /// version of MOVDDUP. 4031 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) { 4032 EVT VT = N->getValueType(0); 4033 4034 if (VT.getSizeInBits() != 128) 4035 return false; 4036 4037 int e = VT.getVectorNumElements() / 2; 4038 for (int i = 0; i < e; ++i) 4039 if (!isUndefOrEqual(N->getMaskElt(i), i)) 4040 return false; 4041 for (int i = 0; i < e; ++i) 4042 if (!isUndefOrEqual(N->getMaskElt(e+i), i)) 4043 return false; 4044 return true; 4045 } 4046 4047 /// isVEXTRACTF128Index - Return true if the specified 4048 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is 4049 /// suitable for input to VEXTRACTF128. 4050 bool X86::isVEXTRACTF128Index(SDNode *N) { 4051 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4052 return false; 4053 4054 // The index should be aligned on a 128-bit boundary. 4055 uint64_t Index = 4056 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4057 4058 unsigned VL = N->getValueType(0).getVectorNumElements(); 4059 unsigned VBits = N->getValueType(0).getSizeInBits(); 4060 unsigned ElSize = VBits / VL; 4061 bool Result = (Index * ElSize) % 128 == 0; 4062 4063 return Result; 4064 } 4065 4066 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR 4067 /// operand specifies a subvector insert that is suitable for input to 4068 /// VINSERTF128. 4069 bool X86::isVINSERTF128Index(SDNode *N) { 4070 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4071 return false; 4072 4073 // The index should be aligned on a 128-bit boundary. 4074 uint64_t Index = 4075 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4076 4077 unsigned VL = N->getValueType(0).getVectorNumElements(); 4078 unsigned VBits = N->getValueType(0).getSizeInBits(); 4079 unsigned ElSize = VBits / VL; 4080 bool Result = (Index * ElSize) % 128 == 0; 4081 4082 return Result; 4083 } 4084 4085 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle 4086 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions. 4087 unsigned X86::getShuffleSHUFImmediate(SDNode *N) { 4088 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4089 int NumOperands = SVOp->getValueType(0).getVectorNumElements(); 4090 4091 unsigned Shift = (NumOperands == 4) ? 2 : 1; 4092 unsigned Mask = 0; 4093 for (int i = 0; i < NumOperands; ++i) { 4094 int Val = SVOp->getMaskElt(NumOperands-i-1); 4095 if (Val < 0) Val = 0; 4096 if (Val >= NumOperands) Val -= NumOperands; 4097 Mask |= Val; 4098 if (i != NumOperands - 1) 4099 Mask <<= Shift; 4100 } 4101 return Mask; 4102 } 4103 4104 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle 4105 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction. 4106 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) { 4107 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4108 unsigned Mask = 0; 4109 // 8 nodes, but we only care about the last 4. 4110 for (unsigned i = 7; i >= 4; --i) { 4111 int Val = SVOp->getMaskElt(i); 4112 if (Val >= 0) 4113 Mask |= (Val - 4); 4114 if (i != 4) 4115 Mask <<= 2; 4116 } 4117 return Mask; 4118 } 4119 4120 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle 4121 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction. 4122 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) { 4123 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4124 unsigned Mask = 0; 4125 // 8 nodes, but we only care about the first 4. 4126 for (int i = 3; i >= 0; --i) { 4127 int Val = SVOp->getMaskElt(i); 4128 if (Val >= 0) 4129 Mask |= Val; 4130 if (i != 0) 4131 Mask <<= 2; 4132 } 4133 return Mask; 4134 } 4135 4136 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle 4137 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction. 4138 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) { 4139 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4140 EVT VVT = N->getValueType(0); 4141 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3; 4142 int Val = 0; 4143 4144 unsigned i, e; 4145 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) { 4146 Val = SVOp->getMaskElt(i); 4147 if (Val >= 0) 4148 break; 4149 } 4150 assert(Val - i > 0 && "PALIGNR imm should be positive"); 4151 return (Val - i) * EltSize; 4152 } 4153 4154 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate 4155 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128 4156 /// instructions. 4157 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) { 4158 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4159 llvm_unreachable("Illegal extract subvector for VEXTRACTF128"); 4160 4161 uint64_t Index = 4162 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4163 4164 EVT VecVT = N->getOperand(0).getValueType(); 4165 EVT ElVT = VecVT.getVectorElementType(); 4166 4167 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4168 return Index / NumElemsPerChunk; 4169 } 4170 4171 /// getInsertVINSERTF128Immediate - Return the appropriate immediate 4172 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128 4173 /// instructions. 4174 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) { 4175 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4176 llvm_unreachable("Illegal insert subvector for VINSERTF128"); 4177 4178 uint64_t Index = 4179 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4180 4181 EVT VecVT = N->getValueType(0); 4182 EVT ElVT = VecVT.getVectorElementType(); 4183 4184 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4185 return Index / NumElemsPerChunk; 4186 } 4187 4188 /// isZeroNode - Returns true if Elt is a constant zero or a floating point 4189 /// constant +0.0. 4190 bool X86::isZeroNode(SDValue Elt) { 4191 return ((isa<ConstantSDNode>(Elt) && 4192 cast<ConstantSDNode>(Elt)->isNullValue()) || 4193 (isa<ConstantFPSDNode>(Elt) && 4194 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero())); 4195 } 4196 4197 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in 4198 /// their permute mask. 4199 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp, 4200 SelectionDAG &DAG) { 4201 EVT VT = SVOp->getValueType(0); 4202 unsigned NumElems = VT.getVectorNumElements(); 4203 SmallVector<int, 8> MaskVec; 4204 4205 for (unsigned i = 0; i != NumElems; ++i) { 4206 int idx = SVOp->getMaskElt(i); 4207 if (idx < 0) 4208 MaskVec.push_back(idx); 4209 else if (idx < (int)NumElems) 4210 MaskVec.push_back(idx + NumElems); 4211 else 4212 MaskVec.push_back(idx - NumElems); 4213 } 4214 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1), 4215 SVOp->getOperand(0), &MaskVec[0]); 4216 } 4217 4218 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming 4219 /// the two vector operands have swapped position. 4220 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) { 4221 unsigned NumElems = VT.getVectorNumElements(); 4222 for (unsigned i = 0; i != NumElems; ++i) { 4223 int idx = Mask[i]; 4224 if (idx < 0) 4225 continue; 4226 else if (idx < (int)NumElems) 4227 Mask[i] = idx + NumElems; 4228 else 4229 Mask[i] = idx - NumElems; 4230 } 4231 } 4232 4233 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to 4234 /// match movhlps. The lower half elements should come from upper half of 4235 /// V1 (and in order), and the upper half elements should come from the upper 4236 /// half of V2 (and in order). 4237 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) { 4238 EVT VT = Op->getValueType(0); 4239 if (VT.getSizeInBits() != 128) 4240 return false; 4241 if (VT.getVectorNumElements() != 4) 4242 return false; 4243 for (unsigned i = 0, e = 2; i != e; ++i) 4244 if (!isUndefOrEqual(Op->getMaskElt(i), i+2)) 4245 return false; 4246 for (unsigned i = 2; i != 4; ++i) 4247 if (!isUndefOrEqual(Op->getMaskElt(i), i+4)) 4248 return false; 4249 return true; 4250 } 4251 4252 /// isScalarLoadToVector - Returns true if the node is a scalar load that 4253 /// is promoted to a vector. It also returns the LoadSDNode by reference if 4254 /// required. 4255 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) { 4256 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR) 4257 return false; 4258 N = N->getOperand(0).getNode(); 4259 if (!ISD::isNON_EXTLoad(N)) 4260 return false; 4261 if (LD) 4262 *LD = cast<LoadSDNode>(N); 4263 return true; 4264 } 4265 4266 // Test whether the given value is a vector value which will be legalized 4267 // into a load. 4268 static bool WillBeConstantPoolLoad(SDNode *N) { 4269 if (N->getOpcode() != ISD::BUILD_VECTOR) 4270 return false; 4271 4272 // Check for any non-constant elements. 4273 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 4274 switch (N->getOperand(i).getNode()->getOpcode()) { 4275 case ISD::UNDEF: 4276 case ISD::ConstantFP: 4277 case ISD::Constant: 4278 break; 4279 default: 4280 return false; 4281 } 4282 4283 // Vectors of all-zeros and all-ones are materialized with special 4284 // instructions rather than being loaded. 4285 return !ISD::isBuildVectorAllZeros(N) && 4286 !ISD::isBuildVectorAllOnes(N); 4287 } 4288 4289 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to 4290 /// match movlp{s|d}. The lower half elements should come from lower half of 4291 /// V1 (and in order), and the upper half elements should come from the upper 4292 /// half of V2 (and in order). And since V1 will become the source of the 4293 /// MOVLP, it must be either a vector load or a scalar load to vector. 4294 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, 4295 ShuffleVectorSDNode *Op) { 4296 EVT VT = Op->getValueType(0); 4297 if (VT.getSizeInBits() != 128) 4298 return false; 4299 4300 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1)) 4301 return false; 4302 // Is V2 is a vector load, don't do this transformation. We will try to use 4303 // load folding shufps op. 4304 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2)) 4305 return false; 4306 4307 unsigned NumElems = VT.getVectorNumElements(); 4308 4309 if (NumElems != 2 && NumElems != 4) 4310 return false; 4311 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 4312 if (!isUndefOrEqual(Op->getMaskElt(i), i)) 4313 return false; 4314 for (unsigned i = NumElems/2; i != NumElems; ++i) 4315 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems)) 4316 return false; 4317 return true; 4318 } 4319 4320 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 4321 /// all the same. 4322 static bool isSplatVector(SDNode *N) { 4323 if (N->getOpcode() != ISD::BUILD_VECTOR) 4324 return false; 4325 4326 SDValue SplatValue = N->getOperand(0); 4327 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i) 4328 if (N->getOperand(i) != SplatValue) 4329 return false; 4330 return true; 4331 } 4332 4333 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved 4334 /// to an zero vector. 4335 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode 4336 static bool isZeroShuffle(ShuffleVectorSDNode *N) { 4337 SDValue V1 = N->getOperand(0); 4338 SDValue V2 = N->getOperand(1); 4339 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 4340 for (unsigned i = 0; i != NumElems; ++i) { 4341 int Idx = N->getMaskElt(i); 4342 if (Idx >= (int)NumElems) { 4343 unsigned Opc = V2.getOpcode(); 4344 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode())) 4345 continue; 4346 if (Opc != ISD::BUILD_VECTOR || 4347 !X86::isZeroNode(V2.getOperand(Idx-NumElems))) 4348 return false; 4349 } else if (Idx >= 0) { 4350 unsigned Opc = V1.getOpcode(); 4351 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode())) 4352 continue; 4353 if (Opc != ISD::BUILD_VECTOR || 4354 !X86::isZeroNode(V1.getOperand(Idx))) 4355 return false; 4356 } 4357 } 4358 return true; 4359 } 4360 4361 /// getZeroVector - Returns a vector of specified type with all zero elements. 4362 /// 4363 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG, 4364 DebugLoc dl) { 4365 assert(VT.isVector() && "Expected a vector type"); 4366 4367 // Always build SSE zero vectors as <4 x i32> bitcasted 4368 // to their dest type. This ensures they get CSE'd. 4369 SDValue Vec; 4370 if (VT.getSizeInBits() == 128) { // SSE 4371 if (HasXMMInt) { // SSE2 4372 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4373 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4374 } else { // SSE1 4375 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4376 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst); 4377 } 4378 } else if (VT.getSizeInBits() == 256) { // AVX 4379 // 256-bit logic and arithmetic instructions in AVX are 4380 // all floating-point, no support for integer ops. Default 4381 // to emitting fp zeroed vectors then. 4382 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4383 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4384 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8); 4385 } 4386 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4387 } 4388 4389 /// getOnesVector - Returns a vector of specified type with all bits set. 4390 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two 4391 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their 4392 /// original type, ensuring they get CSE'd. 4393 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) { 4394 assert(VT.isVector() && "Expected a vector type"); 4395 assert((VT.is128BitVector() || VT.is256BitVector()) 4396 && "Expected a 128-bit or 256-bit vector type"); 4397 4398 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32); 4399 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, 4400 Cst, Cst, Cst, Cst); 4401 4402 if (VT.is256BitVector()) { 4403 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32), 4404 Vec, DAG.getConstant(0, MVT::i32), DAG, dl); 4405 Vec = Insert128BitVector(InsV, Vec, 4406 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl); 4407 } 4408 4409 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4410 } 4411 4412 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements 4413 /// that point to V2 points to its first element. 4414 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 4415 EVT VT = SVOp->getValueType(0); 4416 unsigned NumElems = VT.getVectorNumElements(); 4417 4418 bool Changed = false; 4419 SmallVector<int, 8> MaskVec; 4420 SVOp->getMask(MaskVec); 4421 4422 for (unsigned i = 0; i != NumElems; ++i) { 4423 if (MaskVec[i] > (int)NumElems) { 4424 MaskVec[i] = NumElems; 4425 Changed = true; 4426 } 4427 } 4428 if (Changed) 4429 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0), 4430 SVOp->getOperand(1), &MaskVec[0]); 4431 return SDValue(SVOp, 0); 4432 } 4433 4434 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd 4435 /// operation of specified width. 4436 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4437 SDValue V2) { 4438 unsigned NumElems = VT.getVectorNumElements(); 4439 SmallVector<int, 8> Mask; 4440 Mask.push_back(NumElems); 4441 for (unsigned i = 1; i != NumElems; ++i) 4442 Mask.push_back(i); 4443 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4444 } 4445 4446 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation. 4447 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4448 SDValue V2) { 4449 unsigned NumElems = VT.getVectorNumElements(); 4450 SmallVector<int, 8> Mask; 4451 for (unsigned i = 0, e = NumElems/2; i != e; ++i) { 4452 Mask.push_back(i); 4453 Mask.push_back(i + NumElems); 4454 } 4455 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4456 } 4457 4458 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation. 4459 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4460 SDValue V2) { 4461 unsigned NumElems = VT.getVectorNumElements(); 4462 unsigned Half = NumElems/2; 4463 SmallVector<int, 8> Mask; 4464 for (unsigned i = 0; i != Half; ++i) { 4465 Mask.push_back(i + Half); 4466 Mask.push_back(i + NumElems + Half); 4467 } 4468 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4469 } 4470 4471 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by 4472 // a generic shuffle instruction because the target has no such instructions. 4473 // Generate shuffles which repeat i16 and i8 several times until they can be 4474 // represented by v4f32 and then be manipulated by target suported shuffles. 4475 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) { 4476 EVT VT = V.getValueType(); 4477 int NumElems = VT.getVectorNumElements(); 4478 DebugLoc dl = V.getDebugLoc(); 4479 4480 while (NumElems > 4) { 4481 if (EltNo < NumElems/2) { 4482 V = getUnpackl(DAG, dl, VT, V, V); 4483 } else { 4484 V = getUnpackh(DAG, dl, VT, V, V); 4485 EltNo -= NumElems/2; 4486 } 4487 NumElems >>= 1; 4488 } 4489 return V; 4490 } 4491 4492 /// getLegalSplat - Generate a legal splat with supported x86 shuffles 4493 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) { 4494 EVT VT = V.getValueType(); 4495 DebugLoc dl = V.getDebugLoc(); 4496 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256) 4497 && "Vector size not supported"); 4498 4499 if (VT.getSizeInBits() == 128) { 4500 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V); 4501 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo }; 4502 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32), 4503 &SplatMask[0]); 4504 } else { 4505 // To use VPERMILPS to splat scalars, the second half of indicies must 4506 // refer to the higher part, which is a duplication of the lower one, 4507 // because VPERMILPS can only handle in-lane permutations. 4508 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo, 4509 EltNo+4, EltNo+4, EltNo+4, EltNo+4 }; 4510 4511 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V); 4512 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32), 4513 &SplatMask[0]); 4514 } 4515 4516 return DAG.getNode(ISD::BITCAST, dl, VT, V); 4517 } 4518 4519 /// PromoteSplat - Splat is promoted to target supported vector shuffles. 4520 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) { 4521 EVT SrcVT = SV->getValueType(0); 4522 SDValue V1 = SV->getOperand(0); 4523 DebugLoc dl = SV->getDebugLoc(); 4524 4525 int EltNo = SV->getSplatIndex(); 4526 int NumElems = SrcVT.getVectorNumElements(); 4527 unsigned Size = SrcVT.getSizeInBits(); 4528 4529 assert(((Size == 128 && NumElems > 4) || Size == 256) && 4530 "Unknown how to promote splat for type"); 4531 4532 // Extract the 128-bit part containing the splat element and update 4533 // the splat element index when it refers to the higher register. 4534 if (Size == 256) { 4535 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0; 4536 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl); 4537 if (Idx > 0) 4538 EltNo -= NumElems/2; 4539 } 4540 4541 // All i16 and i8 vector types can't be used directly by a generic shuffle 4542 // instruction because the target has no such instruction. Generate shuffles 4543 // which repeat i16 and i8 several times until they fit in i32, and then can 4544 // be manipulated by target suported shuffles. 4545 EVT EltVT = SrcVT.getVectorElementType(); 4546 if (EltVT == MVT::i8 || EltVT == MVT::i16) 4547 V1 = PromoteSplati8i16(V1, DAG, EltNo); 4548 4549 // Recreate the 256-bit vector and place the same 128-bit vector 4550 // into the low and high part. This is necessary because we want 4551 // to use VPERM* to shuffle the vectors 4552 if (Size == 256) { 4553 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1, 4554 DAG.getConstant(0, MVT::i32), DAG, dl); 4555 V1 = Insert128BitVector(InsV, V1, 4556 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl); 4557 } 4558 4559 return getLegalSplat(DAG, V1, EltNo); 4560 } 4561 4562 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified 4563 /// vector of zero or undef vector. This produces a shuffle where the low 4564 /// element of V2 is swizzled into the zero/undef vector, landing at element 4565 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3). 4566 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx, 4567 bool isZero, bool HasXMMInt, 4568 SelectionDAG &DAG) { 4569 EVT VT = V2.getValueType(); 4570 SDValue V1 = isZero 4571 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT); 4572 unsigned NumElems = VT.getVectorNumElements(); 4573 SmallVector<int, 16> MaskVec; 4574 for (unsigned i = 0; i != NumElems; ++i) 4575 // If this is the insertion idx, put the low elt of V2 here. 4576 MaskVec.push_back(i == Idx ? NumElems : i); 4577 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]); 4578 } 4579 4580 /// getShuffleScalarElt - Returns the scalar element that will make up the ith 4581 /// element of the result of the vector shuffle. 4582 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG, 4583 unsigned Depth) { 4584 if (Depth == 6) 4585 return SDValue(); // Limit search depth. 4586 4587 SDValue V = SDValue(N, 0); 4588 EVT VT = V.getValueType(); 4589 unsigned Opcode = V.getOpcode(); 4590 4591 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars. 4592 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) { 4593 Index = SV->getMaskElt(Index); 4594 4595 if (Index < 0) 4596 return DAG.getUNDEF(VT.getVectorElementType()); 4597 4598 int NumElems = VT.getVectorNumElements(); 4599 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1); 4600 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1); 4601 } 4602 4603 // Recurse into target specific vector shuffles to find scalars. 4604 if (isTargetShuffle(Opcode)) { 4605 int NumElems = VT.getVectorNumElements(); 4606 SmallVector<unsigned, 16> ShuffleMask; 4607 SDValue ImmN; 4608 4609 switch(Opcode) { 4610 case X86ISD::SHUFPS: 4611 case X86ISD::SHUFPD: 4612 ImmN = N->getOperand(N->getNumOperands()-1); 4613 DecodeSHUFPSMask(NumElems, 4614 cast<ConstantSDNode>(ImmN)->getZExtValue(), 4615 ShuffleMask); 4616 break; 4617 case X86ISD::PUNPCKHBW: 4618 case X86ISD::PUNPCKHWD: 4619 case X86ISD::PUNPCKHDQ: 4620 case X86ISD::PUNPCKHQDQ: 4621 DecodePUNPCKHMask(NumElems, ShuffleMask); 4622 break; 4623 case X86ISD::UNPCKHPS: 4624 case X86ISD::UNPCKHPD: 4625 case X86ISD::VUNPCKHPSY: 4626 case X86ISD::VUNPCKHPDY: 4627 DecodeUNPCKHPMask(NumElems, ShuffleMask); 4628 break; 4629 case X86ISD::PUNPCKLBW: 4630 case X86ISD::PUNPCKLWD: 4631 case X86ISD::PUNPCKLDQ: 4632 case X86ISD::PUNPCKLQDQ: 4633 DecodePUNPCKLMask(VT, ShuffleMask); 4634 break; 4635 case X86ISD::UNPCKLPS: 4636 case X86ISD::UNPCKLPD: 4637 case X86ISD::VUNPCKLPSY: 4638 case X86ISD::VUNPCKLPDY: 4639 DecodeUNPCKLPMask(VT, ShuffleMask); 4640 break; 4641 case X86ISD::MOVHLPS: 4642 DecodeMOVHLPSMask(NumElems, ShuffleMask); 4643 break; 4644 case X86ISD::MOVLHPS: 4645 DecodeMOVLHPSMask(NumElems, ShuffleMask); 4646 break; 4647 case X86ISD::PSHUFD: 4648 ImmN = N->getOperand(N->getNumOperands()-1); 4649 DecodePSHUFMask(NumElems, 4650 cast<ConstantSDNode>(ImmN)->getZExtValue(), 4651 ShuffleMask); 4652 break; 4653 case X86ISD::PSHUFHW: 4654 ImmN = N->getOperand(N->getNumOperands()-1); 4655 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 4656 ShuffleMask); 4657 break; 4658 case X86ISD::PSHUFLW: 4659 ImmN = N->getOperand(N->getNumOperands()-1); 4660 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 4661 ShuffleMask); 4662 break; 4663 case X86ISD::MOVSS: 4664 case X86ISD::MOVSD: { 4665 // The index 0 always comes from the first element of the second source, 4666 // this is why MOVSS and MOVSD are used in the first place. The other 4667 // elements come from the other positions of the first source vector. 4668 unsigned OpNum = (Index == 0) ? 1 : 0; 4669 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG, 4670 Depth+1); 4671 } 4672 case X86ISD::VPERMILPS: 4673 ImmN = N->getOperand(N->getNumOperands()-1); 4674 DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4675 ShuffleMask); 4676 break; 4677 case X86ISD::VPERMILPSY: 4678 ImmN = N->getOperand(N->getNumOperands()-1); 4679 DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4680 ShuffleMask); 4681 break; 4682 case X86ISD::VPERMILPD: 4683 ImmN = N->getOperand(N->getNumOperands()-1); 4684 DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4685 ShuffleMask); 4686 break; 4687 case X86ISD::VPERMILPDY: 4688 ImmN = N->getOperand(N->getNumOperands()-1); 4689 DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4690 ShuffleMask); 4691 break; 4692 case X86ISD::VPERM2F128: 4693 ImmN = N->getOperand(N->getNumOperands()-1); 4694 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4695 ShuffleMask); 4696 break; 4697 case X86ISD::MOVDDUP: 4698 case X86ISD::MOVLHPD: 4699 case X86ISD::MOVLPD: 4700 case X86ISD::MOVLPS: 4701 case X86ISD::MOVSHDUP: 4702 case X86ISD::MOVSLDUP: 4703 case X86ISD::PALIGN: 4704 return SDValue(); // Not yet implemented. 4705 default: 4706 assert(0 && "unknown target shuffle node"); 4707 return SDValue(); 4708 } 4709 4710 Index = ShuffleMask[Index]; 4711 if (Index < 0) 4712 return DAG.getUNDEF(VT.getVectorElementType()); 4713 4714 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1); 4715 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, 4716 Depth+1); 4717 } 4718 4719 // Actual nodes that may contain scalar elements 4720 if (Opcode == ISD::BITCAST) { 4721 V = V.getOperand(0); 4722 EVT SrcVT = V.getValueType(); 4723 unsigned NumElems = VT.getVectorNumElements(); 4724 4725 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems) 4726 return SDValue(); 4727 } 4728 4729 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 4730 return (Index == 0) ? V.getOperand(0) 4731 : DAG.getUNDEF(VT.getVectorElementType()); 4732 4733 if (V.getOpcode() == ISD::BUILD_VECTOR) 4734 return V.getOperand(Index); 4735 4736 return SDValue(); 4737 } 4738 4739 /// getNumOfConsecutiveZeros - Return the number of elements of a vector 4740 /// shuffle operation which come from a consecutively from a zero. The 4741 /// search can start in two different directions, from left or right. 4742 static 4743 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems, 4744 bool ZerosFromLeft, SelectionDAG &DAG) { 4745 int i = 0; 4746 4747 while (i < NumElems) { 4748 unsigned Index = ZerosFromLeft ? i : NumElems-i-1; 4749 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0); 4750 if (!(Elt.getNode() && 4751 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt)))) 4752 break; 4753 ++i; 4754 } 4755 4756 return i; 4757 } 4758 4759 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to 4760 /// MaskE correspond consecutively to elements from one of the vector operands, 4761 /// starting from its index OpIdx. Also tell OpNum which source vector operand. 4762 static 4763 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE, 4764 int OpIdx, int NumElems, unsigned &OpNum) { 4765 bool SeenV1 = false; 4766 bool SeenV2 = false; 4767 4768 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) { 4769 int Idx = SVOp->getMaskElt(i); 4770 // Ignore undef indicies 4771 if (Idx < 0) 4772 continue; 4773 4774 if (Idx < NumElems) 4775 SeenV1 = true; 4776 else 4777 SeenV2 = true; 4778 4779 // Only accept consecutive elements from the same vector 4780 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2)) 4781 return false; 4782 } 4783 4784 OpNum = SeenV1 ? 0 : 1; 4785 return true; 4786 } 4787 4788 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a 4789 /// logical left shift of a vector. 4790 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4791 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4792 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4793 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4794 false /* check zeros from right */, DAG); 4795 unsigned OpSrc; 4796 4797 if (!NumZeros) 4798 return false; 4799 4800 // Considering the elements in the mask that are not consecutive zeros, 4801 // check if they consecutively come from only one of the source vectors. 4802 // 4803 // V1 = {X, A, B, C} 0 4804 // \ \ \ / 4805 // vector_shuffle V1, V2 <1, 2, 3, X> 4806 // 4807 if (!isShuffleMaskConsecutive(SVOp, 4808 0, // Mask Start Index 4809 NumElems-NumZeros-1, // Mask End Index 4810 NumZeros, // Where to start looking in the src vector 4811 NumElems, // Number of elements in vector 4812 OpSrc)) // Which source operand ? 4813 return false; 4814 4815 isLeft = false; 4816 ShAmt = NumZeros; 4817 ShVal = SVOp->getOperand(OpSrc); 4818 return true; 4819 } 4820 4821 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a 4822 /// logical left shift of a vector. 4823 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4824 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4825 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4826 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4827 true /* check zeros from left */, DAG); 4828 unsigned OpSrc; 4829 4830 if (!NumZeros) 4831 return false; 4832 4833 // Considering the elements in the mask that are not consecutive zeros, 4834 // check if they consecutively come from only one of the source vectors. 4835 // 4836 // 0 { A, B, X, X } = V2 4837 // / \ / / 4838 // vector_shuffle V1, V2 <X, X, 4, 5> 4839 // 4840 if (!isShuffleMaskConsecutive(SVOp, 4841 NumZeros, // Mask Start Index 4842 NumElems-1, // Mask End Index 4843 0, // Where to start looking in the src vector 4844 NumElems, // Number of elements in vector 4845 OpSrc)) // Which source operand ? 4846 return false; 4847 4848 isLeft = true; 4849 ShAmt = NumZeros; 4850 ShVal = SVOp->getOperand(OpSrc); 4851 return true; 4852 } 4853 4854 /// isVectorShift - Returns true if the shuffle can be implemented as a 4855 /// logical left or right shift of a vector. 4856 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4857 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4858 // Although the logic below support any bitwidth size, there are no 4859 // shift instructions which handle more than 128-bit vectors. 4860 if (SVOp->getValueType(0).getSizeInBits() > 128) 4861 return false; 4862 4863 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) || 4864 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt)) 4865 return true; 4866 4867 return false; 4868 } 4869 4870 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8. 4871 /// 4872 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros, 4873 unsigned NumNonZero, unsigned NumZero, 4874 SelectionDAG &DAG, 4875 const TargetLowering &TLI) { 4876 if (NumNonZero > 8) 4877 return SDValue(); 4878 4879 DebugLoc dl = Op.getDebugLoc(); 4880 SDValue V(0, 0); 4881 bool First = true; 4882 for (unsigned i = 0; i < 16; ++i) { 4883 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0; 4884 if (ThisIsNonZero && First) { 4885 if (NumZero) 4886 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4887 else 4888 V = DAG.getUNDEF(MVT::v8i16); 4889 First = false; 4890 } 4891 4892 if ((i & 1) != 0) { 4893 SDValue ThisElt(0, 0), LastElt(0, 0); 4894 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0; 4895 if (LastIsNonZero) { 4896 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl, 4897 MVT::i16, Op.getOperand(i-1)); 4898 } 4899 if (ThisIsNonZero) { 4900 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i)); 4901 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, 4902 ThisElt, DAG.getConstant(8, MVT::i8)); 4903 if (LastIsNonZero) 4904 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt); 4905 } else 4906 ThisElt = LastElt; 4907 4908 if (ThisElt.getNode()) 4909 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt, 4910 DAG.getIntPtrConstant(i/2)); 4911 } 4912 } 4913 4914 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V); 4915 } 4916 4917 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16. 4918 /// 4919 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros, 4920 unsigned NumNonZero, unsigned NumZero, 4921 SelectionDAG &DAG, 4922 const TargetLowering &TLI) { 4923 if (NumNonZero > 4) 4924 return SDValue(); 4925 4926 DebugLoc dl = Op.getDebugLoc(); 4927 SDValue V(0, 0); 4928 bool First = true; 4929 for (unsigned i = 0; i < 8; ++i) { 4930 bool isNonZero = (NonZeros & (1 << i)) != 0; 4931 if (isNonZero) { 4932 if (First) { 4933 if (NumZero) 4934 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4935 else 4936 V = DAG.getUNDEF(MVT::v8i16); 4937 First = false; 4938 } 4939 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, 4940 MVT::v8i16, V, Op.getOperand(i), 4941 DAG.getIntPtrConstant(i)); 4942 } 4943 } 4944 4945 return V; 4946 } 4947 4948 /// getVShift - Return a vector logical shift node. 4949 /// 4950 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, 4951 unsigned NumBits, SelectionDAG &DAG, 4952 const TargetLowering &TLI, DebugLoc dl) { 4953 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift"); 4954 EVT ShVT = MVT::v2i64; 4955 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL; 4956 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp); 4957 return DAG.getNode(ISD::BITCAST, dl, VT, 4958 DAG.getNode(Opc, dl, ShVT, SrcOp, 4959 DAG.getConstant(NumBits, 4960 TLI.getShiftAmountTy(SrcOp.getValueType())))); 4961 } 4962 4963 SDValue 4964 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl, 4965 SelectionDAG &DAG) const { 4966 4967 // Check if the scalar load can be widened into a vector load. And if 4968 // the address is "base + cst" see if the cst can be "absorbed" into 4969 // the shuffle mask. 4970 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) { 4971 SDValue Ptr = LD->getBasePtr(); 4972 if (!ISD::isNormalLoad(LD) || LD->isVolatile()) 4973 return SDValue(); 4974 EVT PVT = LD->getValueType(0); 4975 if (PVT != MVT::i32 && PVT != MVT::f32) 4976 return SDValue(); 4977 4978 int FI = -1; 4979 int64_t Offset = 0; 4980 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) { 4981 FI = FINode->getIndex(); 4982 Offset = 0; 4983 } else if (DAG.isBaseWithConstantOffset(Ptr) && 4984 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 4985 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 4986 Offset = Ptr.getConstantOperandVal(1); 4987 Ptr = Ptr.getOperand(0); 4988 } else { 4989 return SDValue(); 4990 } 4991 4992 // FIXME: 256-bit vector instructions don't require a strict alignment, 4993 // improve this code to support it better. 4994 unsigned RequiredAlign = VT.getSizeInBits()/8; 4995 SDValue Chain = LD->getChain(); 4996 // Make sure the stack object alignment is at least 16 or 32. 4997 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4998 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) { 4999 if (MFI->isFixedObjectIndex(FI)) { 5000 // Can't change the alignment. FIXME: It's possible to compute 5001 // the exact stack offset and reference FI + adjust offset instead. 5002 // If someone *really* cares about this. That's the way to implement it. 5003 return SDValue(); 5004 } else { 5005 MFI->setObjectAlignment(FI, RequiredAlign); 5006 } 5007 } 5008 5009 // (Offset % 16 or 32) must be multiple of 4. Then address is then 5010 // Ptr + (Offset & ~15). 5011 if (Offset < 0) 5012 return SDValue(); 5013 if ((Offset % RequiredAlign) & 3) 5014 return SDValue(); 5015 int64_t StartOffset = Offset & ~(RequiredAlign-1); 5016 if (StartOffset) 5017 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(), 5018 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType())); 5019 5020 int EltNo = (Offset - StartOffset) >> 2; 5021 int NumElems = VT.getVectorNumElements(); 5022 5023 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32; 5024 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems); 5025 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr, 5026 LD->getPointerInfo().getWithOffset(StartOffset), 5027 false, false, false, 0); 5028 5029 // Canonicalize it to a v4i32 or v8i32 shuffle. 5030 SmallVector<int, 8> Mask; 5031 for (int i = 0; i < NumElems; ++i) 5032 Mask.push_back(EltNo); 5033 5034 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1); 5035 return DAG.getNode(ISD::BITCAST, dl, NVT, 5036 DAG.getVectorShuffle(CanonVT, dl, V1, 5037 DAG.getUNDEF(CanonVT),&Mask[0])); 5038 } 5039 5040 return SDValue(); 5041 } 5042 5043 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 5044 /// vector of type 'VT', see if the elements can be replaced by a single large 5045 /// load which has the same value as a build_vector whose operands are 'elts'. 5046 /// 5047 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a 5048 /// 5049 /// FIXME: we'd also like to handle the case where the last elements are zero 5050 /// rather than undef via VZEXT_LOAD, but we do not detect that case today. 5051 /// There's even a handy isZeroNode for that purpose. 5052 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts, 5053 DebugLoc &DL, SelectionDAG &DAG) { 5054 EVT EltVT = VT.getVectorElementType(); 5055 unsigned NumElems = Elts.size(); 5056 5057 LoadSDNode *LDBase = NULL; 5058 unsigned LastLoadedElt = -1U; 5059 5060 // For each element in the initializer, see if we've found a load or an undef. 5061 // If we don't find an initial load element, or later load elements are 5062 // non-consecutive, bail out. 5063 for (unsigned i = 0; i < NumElems; ++i) { 5064 SDValue Elt = Elts[i]; 5065 5066 if (!Elt.getNode() || 5067 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode()))) 5068 return SDValue(); 5069 if (!LDBase) { 5070 if (Elt.getNode()->getOpcode() == ISD::UNDEF) 5071 return SDValue(); 5072 LDBase = cast<LoadSDNode>(Elt.getNode()); 5073 LastLoadedElt = i; 5074 continue; 5075 } 5076 if (Elt.getOpcode() == ISD::UNDEF) 5077 continue; 5078 5079 LoadSDNode *LD = cast<LoadSDNode>(Elt); 5080 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i)) 5081 return SDValue(); 5082 LastLoadedElt = i; 5083 } 5084 5085 // If we have found an entire vector of loads and undefs, then return a large 5086 // load of the entire vector width starting at the base pointer. If we found 5087 // consecutive loads for the low half, generate a vzext_load node. 5088 if (LastLoadedElt == NumElems - 1) { 5089 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16) 5090 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 5091 LDBase->getPointerInfo(), 5092 LDBase->isVolatile(), LDBase->isNonTemporal(), 5093 LDBase->isInvariant(), 0); 5094 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 5095 LDBase->getPointerInfo(), 5096 LDBase->isVolatile(), LDBase->isNonTemporal(), 5097 LDBase->isInvariant(), LDBase->getAlignment()); 5098 } else if (NumElems == 4 && LastLoadedElt == 1 && 5099 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) { 5100 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other); 5101 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() }; 5102 SDValue ResNode = 5103 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64, 5104 LDBase->getPointerInfo(), 5105 LDBase->getAlignment(), 5106 false/*isVolatile*/, true/*ReadMem*/, 5107 false/*WriteMem*/); 5108 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode); 5109 } 5110 return SDValue(); 5111 } 5112 5113 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to 5114 /// a vbroadcast node. We support two patterns: 5115 /// 1. A splat BUILD_VECTOR which uses a single scalar load. 5116 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from 5117 /// a scalar load. 5118 /// The scalar load node is returned when a pattern is found, 5119 /// or SDValue() otherwise. 5120 static SDValue isVectorBroadcast(SDValue &Op) { 5121 EVT VT = Op.getValueType(); 5122 SDValue V = Op; 5123 5124 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 5125 V = V.getOperand(0); 5126 5127 //A suspected load to be broadcasted. 5128 SDValue Ld; 5129 5130 switch (V.getOpcode()) { 5131 default: 5132 // Unknown pattern found. 5133 return SDValue(); 5134 5135 case ISD::BUILD_VECTOR: { 5136 // The BUILD_VECTOR node must be a splat. 5137 if (!isSplatVector(V.getNode())) 5138 return SDValue(); 5139 5140 Ld = V.getOperand(0); 5141 5142 // The suspected load node has several users. Make sure that all 5143 // of its users are from the BUILD_VECTOR node. 5144 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0)) 5145 return SDValue(); 5146 break; 5147 } 5148 5149 case ISD::VECTOR_SHUFFLE: { 5150 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5151 5152 // Shuffles must have a splat mask where the first element is 5153 // broadcasted. 5154 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0) 5155 return SDValue(); 5156 5157 SDValue Sc = Op.getOperand(0); 5158 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR) 5159 return SDValue(); 5160 5161 Ld = Sc.getOperand(0); 5162 5163 // The scalar_to_vector node and the suspected 5164 // load node must have exactly one user. 5165 if (!Sc.hasOneUse() || !Ld.hasOneUse()) 5166 return SDValue(); 5167 break; 5168 } 5169 } 5170 5171 // The scalar source must be a normal load. 5172 if (!ISD::isNormalLoad(Ld.getNode())) 5173 return SDValue(); 5174 5175 bool Is256 = VT.getSizeInBits() == 256; 5176 bool Is128 = VT.getSizeInBits() == 128; 5177 unsigned ScalarSize = Ld.getValueType().getSizeInBits(); 5178 5179 // VBroadcast to YMM 5180 if (Is256 && (ScalarSize == 32 || ScalarSize == 64)) 5181 return Ld; 5182 5183 // VBroadcast to XMM 5184 if (Is128 && (ScalarSize == 32)) 5185 return Ld; 5186 5187 // Unsupported broadcast. 5188 return SDValue(); 5189 } 5190 5191 SDValue 5192 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { 5193 DebugLoc dl = Op.getDebugLoc(); 5194 5195 EVT VT = Op.getValueType(); 5196 EVT ExtVT = VT.getVectorElementType(); 5197 unsigned NumElems = Op.getNumOperands(); 5198 5199 // Vectors containing all zeros can be matched by pxor and xorps later 5200 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 5201 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd 5202 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts. 5203 if (Op.getValueType() == MVT::v4i32 || 5204 Op.getValueType() == MVT::v8i32) 5205 return Op; 5206 5207 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl); 5208 } 5209 5210 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width 5211 // vectors or broken into v4i32 operations on 256-bit vectors. 5212 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 5213 if (Op.getValueType() == MVT::v4i32) 5214 return Op; 5215 5216 return getOnesVector(Op.getValueType(), DAG, dl); 5217 } 5218 5219 SDValue LD = isVectorBroadcast(Op); 5220 if (Subtarget->hasAVX() && LD.getNode()) 5221 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD); 5222 5223 unsigned EVTBits = ExtVT.getSizeInBits(); 5224 5225 unsigned NumZero = 0; 5226 unsigned NumNonZero = 0; 5227 unsigned NonZeros = 0; 5228 bool IsAllConstants = true; 5229 SmallSet<SDValue, 8> Values; 5230 for (unsigned i = 0; i < NumElems; ++i) { 5231 SDValue Elt = Op.getOperand(i); 5232 if (Elt.getOpcode() == ISD::UNDEF) 5233 continue; 5234 Values.insert(Elt); 5235 if (Elt.getOpcode() != ISD::Constant && 5236 Elt.getOpcode() != ISD::ConstantFP) 5237 IsAllConstants = false; 5238 if (X86::isZeroNode(Elt)) 5239 NumZero++; 5240 else { 5241 NonZeros |= (1 << i); 5242 NumNonZero++; 5243 } 5244 } 5245 5246 // All undef vector. Return an UNDEF. All zero vectors were handled above. 5247 if (NumNonZero == 0) 5248 return DAG.getUNDEF(VT); 5249 5250 // Special case for single non-zero, non-undef, element. 5251 if (NumNonZero == 1) { 5252 unsigned Idx = CountTrailingZeros_32(NonZeros); 5253 SDValue Item = Op.getOperand(Idx); 5254 5255 // If this is an insertion of an i64 value on x86-32, and if the top bits of 5256 // the value are obviously zero, truncate the value to i32 and do the 5257 // insertion that way. Only do this if the value is non-constant or if the 5258 // value is a constant being inserted into element 0. It is cheaper to do 5259 // a constant pool load than it is to do a movd + shuffle. 5260 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() && 5261 (!IsAllConstants || Idx == 0)) { 5262 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) { 5263 // Handle SSE only. 5264 assert(VT == MVT::v2i64 && "Expected an SSE value type!"); 5265 EVT VecVT = MVT::v4i32; 5266 unsigned VecElts = 4; 5267 5268 // Truncate the value (which may itself be a constant) to i32, and 5269 // convert it to a vector with movd (S2V+shuffle to zero extend). 5270 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item); 5271 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item); 5272 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 5273 Subtarget->hasXMMInt(), DAG); 5274 5275 // Now we have our 32-bit value zero extended in the low element of 5276 // a vector. If Idx != 0, swizzle it into place. 5277 if (Idx != 0) { 5278 SmallVector<int, 4> Mask; 5279 Mask.push_back(Idx); 5280 for (unsigned i = 1; i != VecElts; ++i) 5281 Mask.push_back(i); 5282 Item = DAG.getVectorShuffle(VecVT, dl, Item, 5283 DAG.getUNDEF(Item.getValueType()), 5284 &Mask[0]); 5285 } 5286 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item); 5287 } 5288 } 5289 5290 // If we have a constant or non-constant insertion into the low element of 5291 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into 5292 // the rest of the elements. This will be matched as movd/movq/movss/movsd 5293 // depending on what the source datatype is. 5294 if (Idx == 0) { 5295 if (NumZero == 0) { 5296 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5297 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 || 5298 (ExtVT == MVT::i64 && Subtarget->is64Bit())) { 5299 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5300 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector. 5301 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(), 5302 DAG); 5303 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) { 5304 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item); 5305 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!"); 5306 EVT MiddleVT = MVT::v4i32; 5307 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item); 5308 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 5309 Subtarget->hasXMMInt(), DAG); 5310 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5311 } 5312 } 5313 5314 // Is it a vector logical left shift? 5315 if (NumElems == 2 && Idx == 1 && 5316 X86::isZeroNode(Op.getOperand(0)) && 5317 !X86::isZeroNode(Op.getOperand(1))) { 5318 unsigned NumBits = VT.getSizeInBits(); 5319 return getVShift(true, VT, 5320 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5321 VT, Op.getOperand(1)), 5322 NumBits/2, DAG, *this, dl); 5323 } 5324 5325 if (IsAllConstants) // Otherwise, it's better to do a constpool load. 5326 return SDValue(); 5327 5328 // Otherwise, if this is a vector with i32 or f32 elements, and the element 5329 // is a non-constant being inserted into an element other than the low one, 5330 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka 5331 // movd/movss) to move this into the low element, then shuffle it into 5332 // place. 5333 if (EVTBits == 32) { 5334 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5335 5336 // Turn it into a shuffle of zero and zero-extended scalar to vector. 5337 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, 5338 Subtarget->hasXMMInt(), DAG); 5339 SmallVector<int, 8> MaskVec; 5340 for (unsigned i = 0; i < NumElems; i++) 5341 MaskVec.push_back(i == Idx ? 0 : 1); 5342 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]); 5343 } 5344 } 5345 5346 // Splat is obviously ok. Let legalizer expand it to a shuffle. 5347 if (Values.size() == 1) { 5348 if (EVTBits == 32) { 5349 // Instead of a shuffle like this: 5350 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0> 5351 // Check if it's possible to issue this instead. 5352 // shuffle (vload ptr)), undef, <1, 1, 1, 1> 5353 unsigned Idx = CountTrailingZeros_32(NonZeros); 5354 SDValue Item = Op.getOperand(Idx); 5355 if (Op.getNode()->isOnlyUserOf(Item.getNode())) 5356 return LowerAsSplatVectorLoad(Item, VT, dl, DAG); 5357 } 5358 return SDValue(); 5359 } 5360 5361 // A vector full of immediates; various special cases are already 5362 // handled, so this is best done with a single constant-pool load. 5363 if (IsAllConstants) 5364 return SDValue(); 5365 5366 // For AVX-length vectors, build the individual 128-bit pieces and use 5367 // shuffles to put them in place. 5368 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) { 5369 SmallVector<SDValue, 32> V; 5370 for (unsigned i = 0; i < NumElems; ++i) 5371 V.push_back(Op.getOperand(i)); 5372 5373 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2); 5374 5375 // Build both the lower and upper subvector. 5376 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2); 5377 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2], 5378 NumElems/2); 5379 5380 // Recreate the wider vector with the lower and upper part. 5381 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower, 5382 DAG.getConstant(0, MVT::i32), DAG, dl); 5383 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32), 5384 DAG, dl); 5385 } 5386 5387 // Let legalizer expand 2-wide build_vectors. 5388 if (EVTBits == 64) { 5389 if (NumNonZero == 1) { 5390 // One half is zero or undef. 5391 unsigned Idx = CountTrailingZeros_32(NonZeros); 5392 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, 5393 Op.getOperand(Idx)); 5394 return getShuffleVectorZeroOrUndef(V2, Idx, true, 5395 Subtarget->hasXMMInt(), DAG); 5396 } 5397 return SDValue(); 5398 } 5399 5400 // If element VT is < 32 bits, convert it to inserts into a zero vector. 5401 if (EVTBits == 8 && NumElems == 16) { 5402 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG, 5403 *this); 5404 if (V.getNode()) return V; 5405 } 5406 5407 if (EVTBits == 16 && NumElems == 8) { 5408 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG, 5409 *this); 5410 if (V.getNode()) return V; 5411 } 5412 5413 // If element VT is == 32 bits, turn it into a number of shuffles. 5414 SmallVector<SDValue, 8> V; 5415 V.resize(NumElems); 5416 if (NumElems == 4 && NumZero > 0) { 5417 for (unsigned i = 0; i < 4; ++i) { 5418 bool isZero = !(NonZeros & (1 << i)); 5419 if (isZero) 5420 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl); 5421 else 5422 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5423 } 5424 5425 for (unsigned i = 0; i < 2; ++i) { 5426 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) { 5427 default: break; 5428 case 0: 5429 V[i] = V[i*2]; // Must be a zero vector. 5430 break; 5431 case 1: 5432 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]); 5433 break; 5434 case 2: 5435 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]); 5436 break; 5437 case 3: 5438 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]); 5439 break; 5440 } 5441 } 5442 5443 SmallVector<int, 8> MaskVec; 5444 bool Reverse = (NonZeros & 0x3) == 2; 5445 for (unsigned i = 0; i < 2; ++i) 5446 MaskVec.push_back(Reverse ? 1-i : i); 5447 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2; 5448 for (unsigned i = 0; i < 2; ++i) 5449 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems); 5450 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]); 5451 } 5452 5453 if (Values.size() > 1 && VT.getSizeInBits() == 128) { 5454 // Check for a build vector of consecutive loads. 5455 for (unsigned i = 0; i < NumElems; ++i) 5456 V[i] = Op.getOperand(i); 5457 5458 // Check for elements which are consecutive loads. 5459 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG); 5460 if (LD.getNode()) 5461 return LD; 5462 5463 // For SSE 4.1, use insertps to put the high elements into the low element. 5464 if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) { 5465 SDValue Result; 5466 if (Op.getOperand(0).getOpcode() != ISD::UNDEF) 5467 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0)); 5468 else 5469 Result = DAG.getUNDEF(VT); 5470 5471 for (unsigned i = 1; i < NumElems; ++i) { 5472 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue; 5473 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result, 5474 Op.getOperand(i), DAG.getIntPtrConstant(i)); 5475 } 5476 return Result; 5477 } 5478 5479 // Otherwise, expand into a number of unpckl*, start by extending each of 5480 // our (non-undef) elements to the full vector width with the element in the 5481 // bottom slot of the vector (which generates no code for SSE). 5482 for (unsigned i = 0; i < NumElems; ++i) { 5483 if (Op.getOperand(i).getOpcode() != ISD::UNDEF) 5484 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5485 else 5486 V[i] = DAG.getUNDEF(VT); 5487 } 5488 5489 // Next, we iteratively mix elements, e.g. for v4f32: 5490 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0> 5491 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1> 5492 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0> 5493 unsigned EltStride = NumElems >> 1; 5494 while (EltStride != 0) { 5495 for (unsigned i = 0; i < EltStride; ++i) { 5496 // If V[i+EltStride] is undef and this is the first round of mixing, 5497 // then it is safe to just drop this shuffle: V[i] is already in the 5498 // right place, the one element (since it's the first round) being 5499 // inserted as undef can be dropped. This isn't safe for successive 5500 // rounds because they will permute elements within both vectors. 5501 if (V[i+EltStride].getOpcode() == ISD::UNDEF && 5502 EltStride == NumElems/2) 5503 continue; 5504 5505 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]); 5506 } 5507 EltStride >>= 1; 5508 } 5509 return V[0]; 5510 } 5511 return SDValue(); 5512 } 5513 5514 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place 5515 // them in a MMX register. This is better than doing a stack convert. 5516 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5517 DebugLoc dl = Op.getDebugLoc(); 5518 EVT ResVT = Op.getValueType(); 5519 5520 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 || 5521 ResVT == MVT::v8i16 || ResVT == MVT::v16i8); 5522 int Mask[2]; 5523 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0)); 5524 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 5525 InVec = Op.getOperand(1); 5526 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5527 unsigned NumElts = ResVT.getVectorNumElements(); 5528 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 5529 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp, 5530 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1)); 5531 } else { 5532 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec); 5533 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 5534 Mask[0] = 0; Mask[1] = 2; 5535 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask); 5536 } 5537 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 5538 } 5539 5540 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction 5541 // to create 256-bit vectors from two other 128-bit ones. 5542 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5543 DebugLoc dl = Op.getDebugLoc(); 5544 EVT ResVT = Op.getValueType(); 5545 5546 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide"); 5547 5548 SDValue V1 = Op.getOperand(0); 5549 SDValue V2 = Op.getOperand(1); 5550 unsigned NumElems = ResVT.getVectorNumElements(); 5551 5552 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1, 5553 DAG.getConstant(0, MVT::i32), DAG, dl); 5554 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32), 5555 DAG, dl); 5556 } 5557 5558 SDValue 5559 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const { 5560 EVT ResVT = Op.getValueType(); 5561 5562 assert(Op.getNumOperands() == 2); 5563 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) && 5564 "Unsupported CONCAT_VECTORS for value type"); 5565 5566 // We support concatenate two MMX registers and place them in a MMX register. 5567 // This is better than doing a stack convert. 5568 if (ResVT.is128BitVector()) 5569 return LowerMMXCONCAT_VECTORS(Op, DAG); 5570 5571 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors 5572 // from two other 128-bit ones. 5573 return LowerAVXCONCAT_VECTORS(Op, DAG); 5574 } 5575 5576 // v8i16 shuffles - Prefer shuffles in the following order: 5577 // 1. [all] pshuflw, pshufhw, optional move 5578 // 2. [ssse3] 1 x pshufb 5579 // 3. [ssse3] 2 x pshufb + 1 x por 5580 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw) 5581 SDValue 5582 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op, 5583 SelectionDAG &DAG) const { 5584 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5585 SDValue V1 = SVOp->getOperand(0); 5586 SDValue V2 = SVOp->getOperand(1); 5587 DebugLoc dl = SVOp->getDebugLoc(); 5588 SmallVector<int, 8> MaskVals; 5589 5590 // Determine if more than 1 of the words in each of the low and high quadwords 5591 // of the result come from the same quadword of one of the two inputs. Undef 5592 // mask values count as coming from any quadword, for better codegen. 5593 unsigned LoQuad[] = { 0, 0, 0, 0 }; 5594 unsigned HiQuad[] = { 0, 0, 0, 0 }; 5595 BitVector InputQuads(4); 5596 for (unsigned i = 0; i < 8; ++i) { 5597 unsigned *Quad = i < 4 ? LoQuad : HiQuad; 5598 int EltIdx = SVOp->getMaskElt(i); 5599 MaskVals.push_back(EltIdx); 5600 if (EltIdx < 0) { 5601 ++Quad[0]; 5602 ++Quad[1]; 5603 ++Quad[2]; 5604 ++Quad[3]; 5605 continue; 5606 } 5607 ++Quad[EltIdx / 4]; 5608 InputQuads.set(EltIdx / 4); 5609 } 5610 5611 int BestLoQuad = -1; 5612 unsigned MaxQuad = 1; 5613 for (unsigned i = 0; i < 4; ++i) { 5614 if (LoQuad[i] > MaxQuad) { 5615 BestLoQuad = i; 5616 MaxQuad = LoQuad[i]; 5617 } 5618 } 5619 5620 int BestHiQuad = -1; 5621 MaxQuad = 1; 5622 for (unsigned i = 0; i < 4; ++i) { 5623 if (HiQuad[i] > MaxQuad) { 5624 BestHiQuad = i; 5625 MaxQuad = HiQuad[i]; 5626 } 5627 } 5628 5629 // For SSSE3, If all 8 words of the result come from only 1 quadword of each 5630 // of the two input vectors, shuffle them into one input vector so only a 5631 // single pshufb instruction is necessary. If There are more than 2 input 5632 // quads, disable the next transformation since it does not help SSSE3. 5633 bool V1Used = InputQuads[0] || InputQuads[1]; 5634 bool V2Used = InputQuads[2] || InputQuads[3]; 5635 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) { 5636 if (InputQuads.count() == 2 && V1Used && V2Used) { 5637 BestLoQuad = InputQuads.find_first(); 5638 BestHiQuad = InputQuads.find_next(BestLoQuad); 5639 } 5640 if (InputQuads.count() > 2) { 5641 BestLoQuad = -1; 5642 BestHiQuad = -1; 5643 } 5644 } 5645 5646 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update 5647 // the shuffle mask. If a quad is scored as -1, that means that it contains 5648 // words from all 4 input quadwords. 5649 SDValue NewV; 5650 if (BestLoQuad >= 0 || BestHiQuad >= 0) { 5651 SmallVector<int, 8> MaskV; 5652 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad); 5653 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad); 5654 NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 5655 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1), 5656 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]); 5657 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV); 5658 5659 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the 5660 // source words for the shuffle, to aid later transformations. 5661 bool AllWordsInNewV = true; 5662 bool InOrder[2] = { true, true }; 5663 for (unsigned i = 0; i != 8; ++i) { 5664 int idx = MaskVals[i]; 5665 if (idx != (int)i) 5666 InOrder[i/4] = false; 5667 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad) 5668 continue; 5669 AllWordsInNewV = false; 5670 break; 5671 } 5672 5673 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV; 5674 if (AllWordsInNewV) { 5675 for (int i = 0; i != 8; ++i) { 5676 int idx = MaskVals[i]; 5677 if (idx < 0) 5678 continue; 5679 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 5680 if ((idx != i) && idx < 4) 5681 pshufhw = false; 5682 if ((idx != i) && idx > 3) 5683 pshuflw = false; 5684 } 5685 V1 = NewV; 5686 V2Used = false; 5687 BestLoQuad = 0; 5688 BestHiQuad = 1; 5689 } 5690 5691 // If we've eliminated the use of V2, and the new mask is a pshuflw or 5692 // pshufhw, that's as cheap as it gets. Return the new shuffle. 5693 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) { 5694 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW; 5695 unsigned TargetMask = 0; 5696 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 5697 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]); 5698 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()): 5699 X86::getShufflePSHUFLWImmediate(NewV.getNode()); 5700 V1 = NewV.getOperand(0); 5701 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG); 5702 } 5703 } 5704 5705 // If we have SSSE3, and all words of the result are from 1 input vector, 5706 // case 2 is generated, otherwise case 3 is generated. If no SSSE3 5707 // is present, fall back to case 4. 5708 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) { 5709 SmallVector<SDValue,16> pshufbMask; 5710 5711 // If we have elements from both input vectors, set the high bit of the 5712 // shuffle mask element to zero out elements that come from V2 in the V1 5713 // mask, and elements that come from V1 in the V2 mask, so that the two 5714 // results can be OR'd together. 5715 bool TwoInputs = V1Used && V2Used; 5716 for (unsigned i = 0; i != 8; ++i) { 5717 int EltIdx = MaskVals[i] * 2; 5718 if (TwoInputs && (EltIdx >= 16)) { 5719 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5720 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5721 continue; 5722 } 5723 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5724 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8)); 5725 } 5726 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1); 5727 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5728 DAG.getNode(ISD::BUILD_VECTOR, dl, 5729 MVT::v16i8, &pshufbMask[0], 16)); 5730 if (!TwoInputs) 5731 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5732 5733 // Calculate the shuffle mask for the second input, shuffle it, and 5734 // OR it with the first shuffled input. 5735 pshufbMask.clear(); 5736 for (unsigned i = 0; i != 8; ++i) { 5737 int EltIdx = MaskVals[i] * 2; 5738 if (EltIdx < 16) { 5739 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5740 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5741 continue; 5742 } 5743 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 5744 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8)); 5745 } 5746 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2); 5747 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5748 DAG.getNode(ISD::BUILD_VECTOR, dl, 5749 MVT::v16i8, &pshufbMask[0], 16)); 5750 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5751 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5752 } 5753 5754 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order, 5755 // and update MaskVals with new element order. 5756 BitVector InOrder(8); 5757 if (BestLoQuad >= 0) { 5758 SmallVector<int, 8> MaskV; 5759 for (int i = 0; i != 4; ++i) { 5760 int idx = MaskVals[i]; 5761 if (idx < 0) { 5762 MaskV.push_back(-1); 5763 InOrder.set(i); 5764 } else if ((idx / 4) == BestLoQuad) { 5765 MaskV.push_back(idx & 3); 5766 InOrder.set(i); 5767 } else { 5768 MaskV.push_back(-1); 5769 } 5770 } 5771 for (unsigned i = 4; i != 8; ++i) 5772 MaskV.push_back(i); 5773 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5774 &MaskV[0]); 5775 5776 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && 5777 (Subtarget->hasSSSE3() || Subtarget->hasAVX())) 5778 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16, 5779 NewV.getOperand(0), 5780 X86::getShufflePSHUFLWImmediate(NewV.getNode()), 5781 DAG); 5782 } 5783 5784 // If BestHi >= 0, generate a pshufhw to put the high elements in order, 5785 // and update MaskVals with the new element order. 5786 if (BestHiQuad >= 0) { 5787 SmallVector<int, 8> MaskV; 5788 for (unsigned i = 0; i != 4; ++i) 5789 MaskV.push_back(i); 5790 for (unsigned i = 4; i != 8; ++i) { 5791 int idx = MaskVals[i]; 5792 if (idx < 0) { 5793 MaskV.push_back(-1); 5794 InOrder.set(i); 5795 } else if ((idx / 4) == BestHiQuad) { 5796 MaskV.push_back((idx & 3) + 4); 5797 InOrder.set(i); 5798 } else { 5799 MaskV.push_back(-1); 5800 } 5801 } 5802 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5803 &MaskV[0]); 5804 5805 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && 5806 (Subtarget->hasSSSE3() || Subtarget->hasAVX())) 5807 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16, 5808 NewV.getOperand(0), 5809 X86::getShufflePSHUFHWImmediate(NewV.getNode()), 5810 DAG); 5811 } 5812 5813 // In case BestHi & BestLo were both -1, which means each quadword has a word 5814 // from each of the four input quadwords, calculate the InOrder bitvector now 5815 // before falling through to the insert/extract cleanup. 5816 if (BestLoQuad == -1 && BestHiQuad == -1) { 5817 NewV = V1; 5818 for (int i = 0; i != 8; ++i) 5819 if (MaskVals[i] < 0 || MaskVals[i] == i) 5820 InOrder.set(i); 5821 } 5822 5823 // The other elements are put in the right place using pextrw and pinsrw. 5824 for (unsigned i = 0; i != 8; ++i) { 5825 if (InOrder[i]) 5826 continue; 5827 int EltIdx = MaskVals[i]; 5828 if (EltIdx < 0) 5829 continue; 5830 SDValue ExtOp = (EltIdx < 8) 5831 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1, 5832 DAG.getIntPtrConstant(EltIdx)) 5833 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2, 5834 DAG.getIntPtrConstant(EltIdx - 8)); 5835 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp, 5836 DAG.getIntPtrConstant(i)); 5837 } 5838 return NewV; 5839 } 5840 5841 // v16i8 shuffles - Prefer shuffles in the following order: 5842 // 1. [ssse3] 1 x pshufb 5843 // 2. [ssse3] 2 x pshufb + 1 x por 5844 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw 5845 static 5846 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp, 5847 SelectionDAG &DAG, 5848 const X86TargetLowering &TLI) { 5849 SDValue V1 = SVOp->getOperand(0); 5850 SDValue V2 = SVOp->getOperand(1); 5851 DebugLoc dl = SVOp->getDebugLoc(); 5852 SmallVector<int, 16> MaskVals; 5853 SVOp->getMask(MaskVals); 5854 5855 // If we have SSSE3, case 1 is generated when all result bytes come from 5856 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is 5857 // present, fall back to case 3. 5858 // FIXME: kill V2Only once shuffles are canonizalized by getNode. 5859 bool V1Only = true; 5860 bool V2Only = true; 5861 for (unsigned i = 0; i < 16; ++i) { 5862 int EltIdx = MaskVals[i]; 5863 if (EltIdx < 0) 5864 continue; 5865 if (EltIdx < 16) 5866 V2Only = false; 5867 else 5868 V1Only = false; 5869 } 5870 5871 // If SSSE3, use 1 pshufb instruction per vector with elements in the result. 5872 if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) { 5873 SmallVector<SDValue,16> pshufbMask; 5874 5875 // If all result elements are from one input vector, then only translate 5876 // undef mask values to 0x80 (zero out result) in the pshufb mask. 5877 // 5878 // Otherwise, we have elements from both input vectors, and must zero out 5879 // elements that come from V2 in the first mask, and V1 in the second mask 5880 // so that we can OR them together. 5881 bool TwoInputs = !(V1Only || V2Only); 5882 for (unsigned i = 0; i != 16; ++i) { 5883 int EltIdx = MaskVals[i]; 5884 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) { 5885 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5886 continue; 5887 } 5888 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5889 } 5890 // If all the elements are from V2, assign it to V1 and return after 5891 // building the first pshufb. 5892 if (V2Only) 5893 V1 = V2; 5894 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5895 DAG.getNode(ISD::BUILD_VECTOR, dl, 5896 MVT::v16i8, &pshufbMask[0], 16)); 5897 if (!TwoInputs) 5898 return V1; 5899 5900 // Calculate the shuffle mask for the second input, shuffle it, and 5901 // OR it with the first shuffled input. 5902 pshufbMask.clear(); 5903 for (unsigned i = 0; i != 16; ++i) { 5904 int EltIdx = MaskVals[i]; 5905 if (EltIdx < 16) { 5906 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5907 continue; 5908 } 5909 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 5910 } 5911 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5912 DAG.getNode(ISD::BUILD_VECTOR, dl, 5913 MVT::v16i8, &pshufbMask[0], 16)); 5914 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5915 } 5916 5917 // No SSSE3 - Calculate in place words and then fix all out of place words 5918 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from 5919 // the 16 different words that comprise the two doublequadword input vectors. 5920 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5921 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 5922 SDValue NewV = V2Only ? V2 : V1; 5923 for (int i = 0; i != 8; ++i) { 5924 int Elt0 = MaskVals[i*2]; 5925 int Elt1 = MaskVals[i*2+1]; 5926 5927 // This word of the result is all undef, skip it. 5928 if (Elt0 < 0 && Elt1 < 0) 5929 continue; 5930 5931 // This word of the result is already in the correct place, skip it. 5932 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1)) 5933 continue; 5934 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17)) 5935 continue; 5936 5937 SDValue Elt0Src = Elt0 < 16 ? V1 : V2; 5938 SDValue Elt1Src = Elt1 < 16 ? V1 : V2; 5939 SDValue InsElt; 5940 5941 // If Elt0 and Elt1 are defined, are consecutive, and can be load 5942 // using a single extract together, load it and store it. 5943 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) { 5944 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5945 DAG.getIntPtrConstant(Elt1 / 2)); 5946 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5947 DAG.getIntPtrConstant(i)); 5948 continue; 5949 } 5950 5951 // If Elt1 is defined, extract it from the appropriate source. If the 5952 // source byte is not also odd, shift the extracted word left 8 bits 5953 // otherwise clear the bottom 8 bits if we need to do an or. 5954 if (Elt1 >= 0) { 5955 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5956 DAG.getIntPtrConstant(Elt1 / 2)); 5957 if ((Elt1 & 1) == 0) 5958 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt, 5959 DAG.getConstant(8, 5960 TLI.getShiftAmountTy(InsElt.getValueType()))); 5961 else if (Elt0 >= 0) 5962 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt, 5963 DAG.getConstant(0xFF00, MVT::i16)); 5964 } 5965 // If Elt0 is defined, extract it from the appropriate source. If the 5966 // source byte is not also even, shift the extracted word right 8 bits. If 5967 // Elt1 was also defined, OR the extracted values together before 5968 // inserting them in the result. 5969 if (Elt0 >= 0) { 5970 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, 5971 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2)); 5972 if ((Elt0 & 1) != 0) 5973 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0, 5974 DAG.getConstant(8, 5975 TLI.getShiftAmountTy(InsElt0.getValueType()))); 5976 else if (Elt1 >= 0) 5977 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0, 5978 DAG.getConstant(0x00FF, MVT::i16)); 5979 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0) 5980 : InsElt0; 5981 } 5982 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5983 DAG.getIntPtrConstant(i)); 5984 } 5985 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV); 5986 } 5987 5988 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide 5989 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be 5990 /// done when every pair / quad of shuffle mask elements point to elements in 5991 /// the right sequence. e.g. 5992 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15> 5993 static 5994 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp, 5995 SelectionDAG &DAG, DebugLoc dl) { 5996 EVT VT = SVOp->getValueType(0); 5997 SDValue V1 = SVOp->getOperand(0); 5998 SDValue V2 = SVOp->getOperand(1); 5999 unsigned NumElems = VT.getVectorNumElements(); 6000 unsigned NewWidth = (NumElems == 4) ? 2 : 4; 6001 EVT NewVT; 6002 switch (VT.getSimpleVT().SimpleTy) { 6003 default: assert(false && "Unexpected!"); 6004 case MVT::v4f32: NewVT = MVT::v2f64; break; 6005 case MVT::v4i32: NewVT = MVT::v2i64; break; 6006 case MVT::v8i16: NewVT = MVT::v4i32; break; 6007 case MVT::v16i8: NewVT = MVT::v4i32; break; 6008 } 6009 6010 int Scale = NumElems / NewWidth; 6011 SmallVector<int, 8> MaskVec; 6012 for (unsigned i = 0; i < NumElems; i += Scale) { 6013 int StartIdx = -1; 6014 for (int j = 0; j < Scale; ++j) { 6015 int EltIdx = SVOp->getMaskElt(i+j); 6016 if (EltIdx < 0) 6017 continue; 6018 if (StartIdx == -1) 6019 StartIdx = EltIdx - (EltIdx % Scale); 6020 if (EltIdx != StartIdx + j) 6021 return SDValue(); 6022 } 6023 if (StartIdx == -1) 6024 MaskVec.push_back(-1); 6025 else 6026 MaskVec.push_back(StartIdx / Scale); 6027 } 6028 6029 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1); 6030 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2); 6031 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]); 6032 } 6033 6034 /// getVZextMovL - Return a zero-extending vector move low node. 6035 /// 6036 static SDValue getVZextMovL(EVT VT, EVT OpVT, 6037 SDValue SrcOp, SelectionDAG &DAG, 6038 const X86Subtarget *Subtarget, DebugLoc dl) { 6039 if (VT == MVT::v2f64 || VT == MVT::v4f32) { 6040 LoadSDNode *LD = NULL; 6041 if (!isScalarLoadToVector(SrcOp.getNode(), &LD)) 6042 LD = dyn_cast<LoadSDNode>(SrcOp); 6043 if (!LD) { 6044 // movssrr and movsdrr do not clear top bits. Try to use movd, movq 6045 // instead. 6046 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32; 6047 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) && 6048 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 6049 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST && 6050 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) { 6051 // PR2108 6052 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32; 6053 return DAG.getNode(ISD::BITCAST, dl, VT, 6054 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6055 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6056 OpVT, 6057 SrcOp.getOperand(0) 6058 .getOperand(0)))); 6059 } 6060 } 6061 } 6062 6063 return DAG.getNode(ISD::BITCAST, dl, VT, 6064 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6065 DAG.getNode(ISD::BITCAST, dl, 6066 OpVT, SrcOp))); 6067 } 6068 6069 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector 6070 /// shuffle node referes to only one lane in the sources. 6071 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) { 6072 EVT VT = SVOp->getValueType(0); 6073 int NumElems = VT.getVectorNumElements(); 6074 int HalfSize = NumElems/2; 6075 SmallVector<int, 16> M; 6076 SVOp->getMask(M); 6077 bool MatchA = false, MatchB = false; 6078 6079 for (int l = 0; l < NumElems*2; l += HalfSize) { 6080 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) { 6081 MatchA = true; 6082 break; 6083 } 6084 } 6085 6086 for (int l = 0; l < NumElems*2; l += HalfSize) { 6087 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) { 6088 MatchB = true; 6089 break; 6090 } 6091 } 6092 6093 return MatchA && MatchB; 6094 } 6095 6096 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles 6097 /// which could not be matched by any known target speficic shuffle 6098 static SDValue 6099 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6100 if (areShuffleHalvesWithinDisjointLanes(SVOp)) { 6101 // If each half of a vector shuffle node referes to only one lane in the 6102 // source vectors, extract each used 128-bit lane and shuffle them using 6103 // 128-bit shuffles. Then, concatenate the results. Otherwise leave 6104 // the work to the legalizer. 6105 DebugLoc dl = SVOp->getDebugLoc(); 6106 EVT VT = SVOp->getValueType(0); 6107 int NumElems = VT.getVectorNumElements(); 6108 int HalfSize = NumElems/2; 6109 6110 // Extract the reference for each half 6111 int FstVecExtractIdx = 0, SndVecExtractIdx = 0; 6112 int FstVecOpNum = 0, SndVecOpNum = 0; 6113 for (int i = 0; i < HalfSize; ++i) { 6114 int Elt = SVOp->getMaskElt(i); 6115 if (SVOp->getMaskElt(i) < 0) 6116 continue; 6117 FstVecOpNum = Elt/NumElems; 6118 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize; 6119 break; 6120 } 6121 for (int i = HalfSize; i < NumElems; ++i) { 6122 int Elt = SVOp->getMaskElt(i); 6123 if (SVOp->getMaskElt(i) < 0) 6124 continue; 6125 SndVecOpNum = Elt/NumElems; 6126 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize; 6127 break; 6128 } 6129 6130 // Extract the subvectors 6131 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum), 6132 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl); 6133 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum), 6134 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl); 6135 6136 // Generate 128-bit shuffles 6137 SmallVector<int, 16> MaskV1, MaskV2; 6138 for (int i = 0; i < HalfSize; ++i) { 6139 int Elt = SVOp->getMaskElt(i); 6140 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize); 6141 } 6142 for (int i = HalfSize; i < NumElems; ++i) { 6143 int Elt = SVOp->getMaskElt(i); 6144 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize); 6145 } 6146 6147 EVT NVT = V1.getValueType(); 6148 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]); 6149 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]); 6150 6151 // Concatenate the result back 6152 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1, 6153 DAG.getConstant(0, MVT::i32), DAG, dl); 6154 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32), 6155 DAG, dl); 6156 } 6157 6158 return SDValue(); 6159 } 6160 6161 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with 6162 /// 4 elements, and match them with several different shuffle types. 6163 static SDValue 6164 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6165 SDValue V1 = SVOp->getOperand(0); 6166 SDValue V2 = SVOp->getOperand(1); 6167 DebugLoc dl = SVOp->getDebugLoc(); 6168 EVT VT = SVOp->getValueType(0); 6169 6170 assert(VT.getSizeInBits() == 128 && "Unsupported vector size"); 6171 6172 SmallVector<std::pair<int, int>, 8> Locs; 6173 Locs.resize(4); 6174 SmallVector<int, 8> Mask1(4U, -1); 6175 SmallVector<int, 8> PermMask; 6176 SVOp->getMask(PermMask); 6177 6178 unsigned NumHi = 0; 6179 unsigned NumLo = 0; 6180 for (unsigned i = 0; i != 4; ++i) { 6181 int Idx = PermMask[i]; 6182 if (Idx < 0) { 6183 Locs[i] = std::make_pair(-1, -1); 6184 } else { 6185 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!"); 6186 if (Idx < 4) { 6187 Locs[i] = std::make_pair(0, NumLo); 6188 Mask1[NumLo] = Idx; 6189 NumLo++; 6190 } else { 6191 Locs[i] = std::make_pair(1, NumHi); 6192 if (2+NumHi < 4) 6193 Mask1[2+NumHi] = Idx; 6194 NumHi++; 6195 } 6196 } 6197 } 6198 6199 if (NumLo <= 2 && NumHi <= 2) { 6200 // If no more than two elements come from either vector. This can be 6201 // implemented with two shuffles. First shuffle gather the elements. 6202 // The second shuffle, which takes the first shuffle as both of its 6203 // vector operands, put the elements into the right order. 6204 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6205 6206 SmallVector<int, 8> Mask2(4U, -1); 6207 6208 for (unsigned i = 0; i != 4; ++i) { 6209 if (Locs[i].first == -1) 6210 continue; 6211 else { 6212 unsigned Idx = (i < 2) ? 0 : 4; 6213 Idx += Locs[i].first * 2 + Locs[i].second; 6214 Mask2[i] = Idx; 6215 } 6216 } 6217 6218 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]); 6219 } else if (NumLo == 3 || NumHi == 3) { 6220 // Otherwise, we must have three elements from one vector, call it X, and 6221 // one element from the other, call it Y. First, use a shufps to build an 6222 // intermediate vector with the one element from Y and the element from X 6223 // that will be in the same half in the final destination (the indexes don't 6224 // matter). Then, use a shufps to build the final vector, taking the half 6225 // containing the element from Y from the intermediate, and the other half 6226 // from X. 6227 if (NumHi == 3) { 6228 // Normalize it so the 3 elements come from V1. 6229 CommuteVectorShuffleMask(PermMask, VT); 6230 std::swap(V1, V2); 6231 } 6232 6233 // Find the element from V2. 6234 unsigned HiIndex; 6235 for (HiIndex = 0; HiIndex < 3; ++HiIndex) { 6236 int Val = PermMask[HiIndex]; 6237 if (Val < 0) 6238 continue; 6239 if (Val >= 4) 6240 break; 6241 } 6242 6243 Mask1[0] = PermMask[HiIndex]; 6244 Mask1[1] = -1; 6245 Mask1[2] = PermMask[HiIndex^1]; 6246 Mask1[3] = -1; 6247 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6248 6249 if (HiIndex >= 2) { 6250 Mask1[0] = PermMask[0]; 6251 Mask1[1] = PermMask[1]; 6252 Mask1[2] = HiIndex & 1 ? 6 : 4; 6253 Mask1[3] = HiIndex & 1 ? 4 : 6; 6254 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6255 } else { 6256 Mask1[0] = HiIndex & 1 ? 2 : 0; 6257 Mask1[1] = HiIndex & 1 ? 0 : 2; 6258 Mask1[2] = PermMask[2]; 6259 Mask1[3] = PermMask[3]; 6260 if (Mask1[2] >= 0) 6261 Mask1[2] += 4; 6262 if (Mask1[3] >= 0) 6263 Mask1[3] += 4; 6264 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]); 6265 } 6266 } 6267 6268 // Break it into (shuffle shuffle_hi, shuffle_lo). 6269 Locs.clear(); 6270 Locs.resize(4); 6271 SmallVector<int,8> LoMask(4U, -1); 6272 SmallVector<int,8> HiMask(4U, -1); 6273 6274 SmallVector<int,8> *MaskPtr = &LoMask; 6275 unsigned MaskIdx = 0; 6276 unsigned LoIdx = 0; 6277 unsigned HiIdx = 2; 6278 for (unsigned i = 0; i != 4; ++i) { 6279 if (i == 2) { 6280 MaskPtr = &HiMask; 6281 MaskIdx = 1; 6282 LoIdx = 0; 6283 HiIdx = 2; 6284 } 6285 int Idx = PermMask[i]; 6286 if (Idx < 0) { 6287 Locs[i] = std::make_pair(-1, -1); 6288 } else if (Idx < 4) { 6289 Locs[i] = std::make_pair(MaskIdx, LoIdx); 6290 (*MaskPtr)[LoIdx] = Idx; 6291 LoIdx++; 6292 } else { 6293 Locs[i] = std::make_pair(MaskIdx, HiIdx); 6294 (*MaskPtr)[HiIdx] = Idx; 6295 HiIdx++; 6296 } 6297 } 6298 6299 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]); 6300 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]); 6301 SmallVector<int, 8> MaskOps; 6302 for (unsigned i = 0; i != 4; ++i) { 6303 if (Locs[i].first == -1) { 6304 MaskOps.push_back(-1); 6305 } else { 6306 unsigned Idx = Locs[i].first * 4 + Locs[i].second; 6307 MaskOps.push_back(Idx); 6308 } 6309 } 6310 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]); 6311 } 6312 6313 static bool MayFoldVectorLoad(SDValue V) { 6314 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6315 V = V.getOperand(0); 6316 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6317 V = V.getOperand(0); 6318 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR && 6319 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF) 6320 // BUILD_VECTOR (load), undef 6321 V = V.getOperand(0); 6322 if (MayFoldLoad(V)) 6323 return true; 6324 return false; 6325 } 6326 6327 // FIXME: the version above should always be used. Since there's 6328 // a bug where several vector shuffles can't be folded because the 6329 // DAG is not updated during lowering and a node claims to have two 6330 // uses while it only has one, use this version, and let isel match 6331 // another instruction if the load really happens to have more than 6332 // one use. Remove this version after this bug get fixed. 6333 // rdar://8434668, PR8156 6334 static bool RelaxedMayFoldVectorLoad(SDValue V) { 6335 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6336 V = V.getOperand(0); 6337 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6338 V = V.getOperand(0); 6339 if (ISD::isNormalLoad(V.getNode())) 6340 return true; 6341 return false; 6342 } 6343 6344 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by 6345 /// a vector extract, and if both can be later optimized into a single load. 6346 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked 6347 /// here because otherwise a target specific shuffle node is going to be 6348 /// emitted for this shuffle, and the optimization not done. 6349 /// FIXME: This is probably not the best approach, but fix the problem 6350 /// until the right path is decided. 6351 static 6352 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG, 6353 const TargetLowering &TLI) { 6354 EVT VT = V.getValueType(); 6355 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V); 6356 6357 // Be sure that the vector shuffle is present in a pattern like this: 6358 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr) 6359 if (!V.hasOneUse()) 6360 return false; 6361 6362 SDNode *N = *V.getNode()->use_begin(); 6363 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 6364 return false; 6365 6366 SDValue EltNo = N->getOperand(1); 6367 if (!isa<ConstantSDNode>(EltNo)) 6368 return false; 6369 6370 // If the bit convert changed the number of elements, it is unsafe 6371 // to examine the mask. 6372 bool HasShuffleIntoBitcast = false; 6373 if (V.getOpcode() == ISD::BITCAST) { 6374 EVT SrcVT = V.getOperand(0).getValueType(); 6375 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements()) 6376 return false; 6377 V = V.getOperand(0); 6378 HasShuffleIntoBitcast = true; 6379 } 6380 6381 // Select the input vector, guarding against out of range extract vector. 6382 unsigned NumElems = VT.getVectorNumElements(); 6383 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6384 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt); 6385 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1); 6386 6387 // Skip one more bit_convert if necessary 6388 if (V.getOpcode() == ISD::BITCAST) 6389 V = V.getOperand(0); 6390 6391 if (ISD::isNormalLoad(V.getNode())) { 6392 // Is the original load suitable? 6393 LoadSDNode *LN0 = cast<LoadSDNode>(V); 6394 6395 // FIXME: avoid the multi-use bug that is preventing lots of 6396 // of foldings to be detected, this is still wrong of course, but 6397 // give the temporary desired behavior, and if it happens that 6398 // the load has real more uses, during isel it will not fold, and 6399 // will generate poor code. 6400 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse() 6401 return false; 6402 6403 if (!HasShuffleIntoBitcast) 6404 return true; 6405 6406 // If there's a bitcast before the shuffle, check if the load type and 6407 // alignment is valid. 6408 unsigned Align = LN0->getAlignment(); 6409 unsigned NewAlign = 6410 TLI.getTargetData()->getABITypeAlignment( 6411 VT.getTypeForEVT(*DAG.getContext())); 6412 6413 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT)) 6414 return false; 6415 } 6416 6417 return true; 6418 } 6419 6420 static 6421 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) { 6422 EVT VT = Op.getValueType(); 6423 6424 // Canonizalize to v2f64. 6425 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 6426 return DAG.getNode(ISD::BITCAST, dl, VT, 6427 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64, 6428 V1, DAG)); 6429 } 6430 6431 static 6432 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, 6433 bool HasXMMInt) { 6434 SDValue V1 = Op.getOperand(0); 6435 SDValue V2 = Op.getOperand(1); 6436 EVT VT = Op.getValueType(); 6437 6438 assert(VT != MVT::v2i64 && "unsupported shuffle type"); 6439 6440 if (HasXMMInt && VT == MVT::v2f64) 6441 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG); 6442 6443 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1) 6444 return DAG.getNode(ISD::BITCAST, dl, VT, 6445 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32, 6446 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1), 6447 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG)); 6448 } 6449 6450 static 6451 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) { 6452 SDValue V1 = Op.getOperand(0); 6453 SDValue V2 = Op.getOperand(1); 6454 EVT VT = Op.getValueType(); 6455 6456 assert((VT == MVT::v4i32 || VT == MVT::v4f32) && 6457 "unsupported shuffle type"); 6458 6459 if (V2.getOpcode() == ISD::UNDEF) 6460 V2 = V1; 6461 6462 // v4i32 or v4f32 6463 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG); 6464 } 6465 6466 static inline unsigned getSHUFPOpcode(EVT VT) { 6467 switch(VT.getSimpleVT().SimpleTy) { 6468 case MVT::v8i32: // Use fp unit for int unpack. 6469 case MVT::v8f32: 6470 case MVT::v4i32: // Use fp unit for int unpack. 6471 case MVT::v4f32: return X86ISD::SHUFPS; 6472 case MVT::v4i64: // Use fp unit for int unpack. 6473 case MVT::v4f64: 6474 case MVT::v2i64: // Use fp unit for int unpack. 6475 case MVT::v2f64: return X86ISD::SHUFPD; 6476 default: 6477 llvm_unreachable("Unknown type for shufp*"); 6478 } 6479 return 0; 6480 } 6481 6482 static 6483 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) { 6484 SDValue V1 = Op.getOperand(0); 6485 SDValue V2 = Op.getOperand(1); 6486 EVT VT = Op.getValueType(); 6487 unsigned NumElems = VT.getVectorNumElements(); 6488 6489 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second 6490 // operand of these instructions is only memory, so check if there's a 6491 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the 6492 // same masks. 6493 bool CanFoldLoad = false; 6494 6495 // Trivial case, when V2 comes from a load. 6496 if (MayFoldVectorLoad(V2)) 6497 CanFoldLoad = true; 6498 6499 // When V1 is a load, it can be folded later into a store in isel, example: 6500 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1) 6501 // turns into: 6502 // (MOVLPSmr addr:$src1, VR128:$src2) 6503 // So, recognize this potential and also use MOVLPS or MOVLPD 6504 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op)) 6505 CanFoldLoad = true; 6506 6507 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6508 if (CanFoldLoad) { 6509 if (HasXMMInt && NumElems == 2) 6510 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG); 6511 6512 if (NumElems == 4) 6513 // If we don't care about the second element, procede to use movss. 6514 if (SVOp->getMaskElt(1) != -1) 6515 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG); 6516 } 6517 6518 // movl and movlp will both match v2i64, but v2i64 is never matched by 6519 // movl earlier because we make it strict to avoid messing with the movlp load 6520 // folding logic (see the code above getMOVLP call). Match it here then, 6521 // this is horrible, but will stay like this until we move all shuffle 6522 // matching to x86 specific nodes. Note that for the 1st condition all 6523 // types are matched with movsd. 6524 if (HasXMMInt) { 6525 // FIXME: isMOVLMask should be checked and matched before getMOVLP, 6526 // as to remove this logic from here, as much as possible 6527 if (NumElems == 2 || !X86::isMOVLMask(SVOp)) 6528 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6529 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6530 } 6531 6532 assert(VT != MVT::v4i32 && "unsupported shuffle type"); 6533 6534 // Invert the operand order and use SHUFPS to match it. 6535 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1, 6536 X86::getShuffleSHUFImmediate(SVOp), DAG); 6537 } 6538 6539 static inline unsigned getUNPCKLOpcode(EVT VT) { 6540 switch(VT.getSimpleVT().SimpleTy) { 6541 case MVT::v4i32: return X86ISD::PUNPCKLDQ; 6542 case MVT::v2i64: return X86ISD::PUNPCKLQDQ; 6543 case MVT::v4f32: return X86ISD::UNPCKLPS; 6544 case MVT::v2f64: return X86ISD::UNPCKLPD; 6545 case MVT::v8i32: // Use fp unit for int unpack. 6546 case MVT::v8f32: return X86ISD::VUNPCKLPSY; 6547 case MVT::v4i64: // Use fp unit for int unpack. 6548 case MVT::v4f64: return X86ISD::VUNPCKLPDY; 6549 case MVT::v16i8: return X86ISD::PUNPCKLBW; 6550 case MVT::v8i16: return X86ISD::PUNPCKLWD; 6551 default: 6552 llvm_unreachable("Unknown type for unpckl"); 6553 } 6554 return 0; 6555 } 6556 6557 static inline unsigned getUNPCKHOpcode(EVT VT) { 6558 switch(VT.getSimpleVT().SimpleTy) { 6559 case MVT::v4i32: return X86ISD::PUNPCKHDQ; 6560 case MVT::v2i64: return X86ISD::PUNPCKHQDQ; 6561 case MVT::v4f32: return X86ISD::UNPCKHPS; 6562 case MVT::v2f64: return X86ISD::UNPCKHPD; 6563 case MVT::v8i32: // Use fp unit for int unpack. 6564 case MVT::v8f32: return X86ISD::VUNPCKHPSY; 6565 case MVT::v4i64: // Use fp unit for int unpack. 6566 case MVT::v4f64: return X86ISD::VUNPCKHPDY; 6567 case MVT::v16i8: return X86ISD::PUNPCKHBW; 6568 case MVT::v8i16: return X86ISD::PUNPCKHWD; 6569 default: 6570 llvm_unreachable("Unknown type for unpckh"); 6571 } 6572 return 0; 6573 } 6574 6575 static inline unsigned getVPERMILOpcode(EVT VT) { 6576 switch(VT.getSimpleVT().SimpleTy) { 6577 case MVT::v4i32: 6578 case MVT::v4f32: return X86ISD::VPERMILPS; 6579 case MVT::v2i64: 6580 case MVT::v2f64: return X86ISD::VPERMILPD; 6581 case MVT::v8i32: 6582 case MVT::v8f32: return X86ISD::VPERMILPSY; 6583 case MVT::v4i64: 6584 case MVT::v4f64: return X86ISD::VPERMILPDY; 6585 default: 6586 llvm_unreachable("Unknown type for vpermil"); 6587 } 6588 return 0; 6589 } 6590 6591 static 6592 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG, 6593 const TargetLowering &TLI, 6594 const X86Subtarget *Subtarget) { 6595 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6596 EVT VT = Op.getValueType(); 6597 DebugLoc dl = Op.getDebugLoc(); 6598 SDValue V1 = Op.getOperand(0); 6599 SDValue V2 = Op.getOperand(1); 6600 6601 if (isZeroShuffle(SVOp)) 6602 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl); 6603 6604 // Handle splat operations 6605 if (SVOp->isSplat()) { 6606 unsigned NumElem = VT.getVectorNumElements(); 6607 int Size = VT.getSizeInBits(); 6608 // Special case, this is the only place now where it's allowed to return 6609 // a vector_shuffle operation without using a target specific node, because 6610 // *hopefully* it will be optimized away by the dag combiner. FIXME: should 6611 // this be moved to DAGCombine instead? 6612 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI)) 6613 return Op; 6614 6615 // Use vbroadcast whenever the splat comes from a foldable load 6616 SDValue LD = isVectorBroadcast(Op); 6617 if (Subtarget->hasAVX() && LD.getNode()) 6618 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD); 6619 6620 // Handle splats by matching through known shuffle masks 6621 if ((Size == 128 && NumElem <= 4) || 6622 (Size == 256 && NumElem < 8)) 6623 return SDValue(); 6624 6625 // All remaning splats are promoted to target supported vector shuffles. 6626 return PromoteSplat(SVOp, DAG); 6627 } 6628 6629 // If the shuffle can be profitably rewritten as a narrower shuffle, then 6630 // do it! 6631 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 6632 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6633 if (NewOp.getNode()) 6634 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp); 6635 } else if ((VT == MVT::v4i32 || 6636 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) { 6637 // FIXME: Figure out a cleaner way to do this. 6638 // Try to make use of movq to zero out the top part. 6639 if (ISD::isBuildVectorAllZeros(V2.getNode())) { 6640 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6641 if (NewOp.getNode()) { 6642 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false)) 6643 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0), 6644 DAG, Subtarget, dl); 6645 } 6646 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) { 6647 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6648 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp))) 6649 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1), 6650 DAG, Subtarget, dl); 6651 } 6652 } 6653 return SDValue(); 6654 } 6655 6656 SDValue 6657 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { 6658 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6659 SDValue V1 = Op.getOperand(0); 6660 SDValue V2 = Op.getOperand(1); 6661 EVT VT = Op.getValueType(); 6662 DebugLoc dl = Op.getDebugLoc(); 6663 unsigned NumElems = VT.getVectorNumElements(); 6664 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF; 6665 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 6666 bool V1IsSplat = false; 6667 bool V2IsSplat = false; 6668 bool HasXMMInt = Subtarget->hasXMMInt(); 6669 MachineFunction &MF = DAG.getMachineFunction(); 6670 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize); 6671 6672 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles"); 6673 6674 // Vector shuffle lowering takes 3 steps: 6675 // 6676 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable 6677 // narrowing and commutation of operands should be handled. 6678 // 2) Matching of shuffles with known shuffle masks to x86 target specific 6679 // shuffle nodes. 6680 // 3) Rewriting of unmatched masks into new generic shuffle operations, 6681 // so the shuffle can be broken into other shuffles and the legalizer can 6682 // try the lowering again. 6683 // 6684 // The general idea is that no vector_shuffle operation should be left to 6685 // be matched during isel, all of them must be converted to a target specific 6686 // node here. 6687 6688 // Normalize the input vectors. Here splats, zeroed vectors, profitable 6689 // narrowing and commutation of operands should be handled. The actual code 6690 // doesn't include all of those, work in progress... 6691 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget); 6692 if (NewOp.getNode()) 6693 return NewOp; 6694 6695 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and 6696 // unpckh_undef). Only use pshufd if speed is more important than size. 6697 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp)) 6698 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG); 6699 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp)) 6700 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 6701 6702 if (X86::isMOVDDUPMask(SVOp) && 6703 (Subtarget->hasSSE3() || Subtarget->hasAVX()) && 6704 V2IsUndef && RelaxedMayFoldVectorLoad(V1)) 6705 return getMOVDDup(Op, dl, V1, DAG); 6706 6707 if (X86::isMOVHLPS_v_undef_Mask(SVOp)) 6708 return getMOVHighToLow(Op, dl, DAG); 6709 6710 // Use to match splats 6711 if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef && 6712 (VT == MVT::v2f64 || VT == MVT::v2i64)) 6713 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 6714 6715 if (X86::isPSHUFDMask(SVOp)) { 6716 // The actual implementation will match the mask in the if above and then 6717 // during isel it can match several different instructions, not only pshufd 6718 // as its name says, sad but true, emulate the behavior for now... 6719 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64))) 6720 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG); 6721 6722 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp); 6723 6724 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32)) 6725 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG); 6726 6727 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1, 6728 TargetMask, DAG); 6729 } 6730 6731 // Check if this can be converted into a logical shift. 6732 bool isLeft = false; 6733 unsigned ShAmt = 0; 6734 SDValue ShVal; 6735 bool isShift = getSubtarget()->hasXMMInt() && 6736 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt); 6737 if (isShift && ShVal.hasOneUse()) { 6738 // If the shifted value has multiple uses, it may be cheaper to use 6739 // v_set0 + movlhps or movhlps, etc. 6740 EVT EltVT = VT.getVectorElementType(); 6741 ShAmt *= EltVT.getSizeInBits(); 6742 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6743 } 6744 6745 if (X86::isMOVLMask(SVOp)) { 6746 if (V1IsUndef) 6747 return V2; 6748 if (ISD::isBuildVectorAllZeros(V1.getNode())) 6749 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl); 6750 if (!X86::isMOVLPMask(SVOp)) { 6751 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64)) 6752 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6753 6754 if (VT == MVT::v4i32 || VT == MVT::v4f32) 6755 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6756 } 6757 } 6758 6759 // FIXME: fold these into legal mask. 6760 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp)) 6761 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt); 6762 6763 if (X86::isMOVHLPSMask(SVOp)) 6764 return getMOVHighToLow(Op, dl, DAG); 6765 6766 if (X86::isMOVSHDUPMask(SVOp, Subtarget)) 6767 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG); 6768 6769 if (X86::isMOVSLDUPMask(SVOp, Subtarget)) 6770 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG); 6771 6772 if (X86::isMOVLPMask(SVOp)) 6773 return getMOVLP(Op, dl, DAG, HasXMMInt); 6774 6775 if (ShouldXformToMOVHLPS(SVOp) || 6776 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp)) 6777 return CommuteVectorShuffle(SVOp, DAG); 6778 6779 if (isShift) { 6780 // No better options. Use a vshl / vsrl. 6781 EVT EltVT = VT.getVectorElementType(); 6782 ShAmt *= EltVT.getSizeInBits(); 6783 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6784 } 6785 6786 bool Commuted = false; 6787 // FIXME: This should also accept a bitcast of a splat? Be careful, not 6788 // 1,1,1,1 -> v8i16 though. 6789 V1IsSplat = isSplatVector(V1.getNode()); 6790 V2IsSplat = isSplatVector(V2.getNode()); 6791 6792 // Canonicalize the splat or undef, if present, to be on the RHS. 6793 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) { 6794 Op = CommuteVectorShuffle(SVOp, DAG); 6795 SVOp = cast<ShuffleVectorSDNode>(Op); 6796 V1 = SVOp->getOperand(0); 6797 V2 = SVOp->getOperand(1); 6798 std::swap(V1IsSplat, V2IsSplat); 6799 std::swap(V1IsUndef, V2IsUndef); 6800 Commuted = true; 6801 } 6802 6803 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) { 6804 // Shuffling low element of v1 into undef, just return v1. 6805 if (V2IsUndef) 6806 return V1; 6807 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which 6808 // the instruction selector will not match, so get a canonical MOVL with 6809 // swapped operands to undo the commute. 6810 return getMOVL(DAG, dl, VT, V2, V1); 6811 } 6812 6813 if (X86::isUNPCKLMask(SVOp)) 6814 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG); 6815 6816 if (X86::isUNPCKHMask(SVOp)) 6817 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG); 6818 6819 if (V2IsSplat) { 6820 // Normalize mask so all entries that point to V2 points to its first 6821 // element then try to match unpck{h|l} again. If match, return a 6822 // new vector_shuffle with the corrected mask. 6823 SDValue NewMask = NormalizeMask(SVOp, DAG); 6824 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask); 6825 if (NSVOp != SVOp) { 6826 if (X86::isUNPCKLMask(NSVOp, true)) { 6827 return NewMask; 6828 } else if (X86::isUNPCKHMask(NSVOp, true)) { 6829 return NewMask; 6830 } 6831 } 6832 } 6833 6834 if (Commuted) { 6835 // Commute is back and try unpck* again. 6836 // FIXME: this seems wrong. 6837 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG); 6838 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp); 6839 6840 if (X86::isUNPCKLMask(NewSVOp)) 6841 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG); 6842 6843 if (X86::isUNPCKHMask(NewSVOp)) 6844 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG); 6845 } 6846 6847 // Normalize the node to match x86 shuffle ops if needed 6848 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp)) 6849 return CommuteVectorShuffle(SVOp, DAG); 6850 6851 // The checks below are all present in isShuffleMaskLegal, but they are 6852 // inlined here right now to enable us to directly emit target specific 6853 // nodes, and remove one by one until they don't return Op anymore. 6854 SmallVector<int, 16> M; 6855 SVOp->getMask(M); 6856 6857 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX())) 6858 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2, 6859 X86::getShufflePALIGNRImmediate(SVOp), 6860 DAG); 6861 6862 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) && 6863 SVOp->getSplatIndex() == 0 && V2IsUndef) { 6864 if (VT == MVT::v2f64) 6865 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG); 6866 if (VT == MVT::v2i64) 6867 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG); 6868 } 6869 6870 if (isPSHUFHWMask(M, VT)) 6871 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1, 6872 X86::getShufflePSHUFHWImmediate(SVOp), 6873 DAG); 6874 6875 if (isPSHUFLWMask(M, VT)) 6876 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1, 6877 X86::getShufflePSHUFLWImmediate(SVOp), 6878 DAG); 6879 6880 if (isSHUFPMask(M, VT)) 6881 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, 6882 X86::getShuffleSHUFImmediate(SVOp), DAG); 6883 6884 if (X86::isUNPCKL_v_undef_Mask(SVOp)) 6885 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG); 6886 if (X86::isUNPCKH_v_undef_Mask(SVOp)) 6887 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 6888 6889 //===--------------------------------------------------------------------===// 6890 // Generate target specific nodes for 128 or 256-bit shuffles only 6891 // supported in the AVX instruction set. 6892 // 6893 6894 // Handle VMOVDDUPY permutations 6895 if (isMOVDDUPYMask(SVOp, Subtarget)) 6896 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG); 6897 6898 // Handle VPERMILPS* permutations 6899 if (isVPERMILPSMask(M, VT, Subtarget)) 6900 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1, 6901 getShuffleVPERMILPSImmediate(SVOp), DAG); 6902 6903 // Handle VPERMILPD* permutations 6904 if (isVPERMILPDMask(M, VT, Subtarget)) 6905 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1, 6906 getShuffleVPERMILPDImmediate(SVOp), DAG); 6907 6908 // Handle VPERM2F128 permutations 6909 if (isVPERM2F128Mask(M, VT, Subtarget)) 6910 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2, 6911 getShuffleVPERM2F128Immediate(SVOp), DAG); 6912 6913 // Handle VSHUFPSY permutations 6914 if (isVSHUFPSYMask(M, VT, Subtarget)) 6915 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, 6916 getShuffleVSHUFPSYImmediate(SVOp), DAG); 6917 6918 // Handle VSHUFPDY permutations 6919 if (isVSHUFPDYMask(M, VT, Subtarget)) 6920 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, 6921 getShuffleVSHUFPDYImmediate(SVOp), DAG); 6922 6923 //===--------------------------------------------------------------------===// 6924 // Since no target specific shuffle was selected for this generic one, 6925 // lower it into other known shuffles. FIXME: this isn't true yet, but 6926 // this is the plan. 6927 // 6928 6929 // Handle v8i16 specifically since SSE can do byte extraction and insertion. 6930 if (VT == MVT::v8i16) { 6931 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG); 6932 if (NewOp.getNode()) 6933 return NewOp; 6934 } 6935 6936 if (VT == MVT::v16i8) { 6937 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this); 6938 if (NewOp.getNode()) 6939 return NewOp; 6940 } 6941 6942 // Handle all 128-bit wide vectors with 4 elements, and match them with 6943 // several different shuffle types. 6944 if (NumElems == 4 && VT.getSizeInBits() == 128) 6945 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG); 6946 6947 // Handle general 256-bit shuffles 6948 if (VT.is256BitVector()) 6949 return LowerVECTOR_SHUFFLE_256(SVOp, DAG); 6950 6951 return SDValue(); 6952 } 6953 6954 SDValue 6955 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, 6956 SelectionDAG &DAG) const { 6957 EVT VT = Op.getValueType(); 6958 DebugLoc dl = Op.getDebugLoc(); 6959 6960 if (Op.getOperand(0).getValueType().getSizeInBits() != 128) 6961 return SDValue(); 6962 6963 if (VT.getSizeInBits() == 8) { 6964 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, 6965 Op.getOperand(0), Op.getOperand(1)); 6966 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 6967 DAG.getValueType(VT)); 6968 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6969 } else if (VT.getSizeInBits() == 16) { 6970 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6971 // If Idx is 0, it's cheaper to do a move instead of a pextrw. 6972 if (Idx == 0) 6973 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 6974 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6975 DAG.getNode(ISD::BITCAST, dl, 6976 MVT::v4i32, 6977 Op.getOperand(0)), 6978 Op.getOperand(1))); 6979 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, 6980 Op.getOperand(0), Op.getOperand(1)); 6981 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 6982 DAG.getValueType(VT)); 6983 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6984 } else if (VT == MVT::f32) { 6985 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy 6986 // the result back to FR32 register. It's only worth matching if the 6987 // result has a single use which is a store or a bitcast to i32. And in 6988 // the case of a store, it's not worth it if the index is a constant 0, 6989 // because a MOVSSmr can be used instead, which is smaller and faster. 6990 if (!Op.hasOneUse()) 6991 return SDValue(); 6992 SDNode *User = *Op.getNode()->use_begin(); 6993 if ((User->getOpcode() != ISD::STORE || 6994 (isa<ConstantSDNode>(Op.getOperand(1)) && 6995 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) && 6996 (User->getOpcode() != ISD::BITCAST || 6997 User->getValueType(0) != MVT::i32)) 6998 return SDValue(); 6999 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7000 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, 7001 Op.getOperand(0)), 7002 Op.getOperand(1)); 7003 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract); 7004 } else if (VT == MVT::i32 || VT == MVT::i64) { 7005 // ExtractPS/pextrq works with constant index. 7006 if (isa<ConstantSDNode>(Op.getOperand(1))) 7007 return Op; 7008 } 7009 return SDValue(); 7010 } 7011 7012 7013 SDValue 7014 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 7015 SelectionDAG &DAG) const { 7016 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7017 return SDValue(); 7018 7019 SDValue Vec = Op.getOperand(0); 7020 EVT VecVT = Vec.getValueType(); 7021 7022 // If this is a 256-bit vector result, first extract the 128-bit vector and 7023 // then extract the element from the 128-bit vector. 7024 if (VecVT.getSizeInBits() == 256) { 7025 DebugLoc dl = Op.getNode()->getDebugLoc(); 7026 unsigned NumElems = VecVT.getVectorNumElements(); 7027 SDValue Idx = Op.getOperand(1); 7028 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7029 7030 // Get the 128-bit vector. 7031 bool Upper = IdxVal >= NumElems/2; 7032 Vec = Extract128BitVector(Vec, 7033 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl); 7034 7035 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec, 7036 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx); 7037 } 7038 7039 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length"); 7040 7041 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) { 7042 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG); 7043 if (Res.getNode()) 7044 return Res; 7045 } 7046 7047 EVT VT = Op.getValueType(); 7048 DebugLoc dl = Op.getDebugLoc(); 7049 // TODO: handle v16i8. 7050 if (VT.getSizeInBits() == 16) { 7051 SDValue Vec = Op.getOperand(0); 7052 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7053 if (Idx == 0) 7054 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 7055 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7056 DAG.getNode(ISD::BITCAST, dl, 7057 MVT::v4i32, Vec), 7058 Op.getOperand(1))); 7059 // Transform it so it match pextrw which produces a 32-bit result. 7060 EVT EltVT = MVT::i32; 7061 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, 7062 Op.getOperand(0), Op.getOperand(1)); 7063 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract, 7064 DAG.getValueType(VT)); 7065 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 7066 } else if (VT.getSizeInBits() == 32) { 7067 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7068 if (Idx == 0) 7069 return Op; 7070 7071 // SHUFPS the element to the lowest double word, then movss. 7072 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 }; 7073 EVT VVT = Op.getOperand(0).getValueType(); 7074 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 7075 DAG.getUNDEF(VVT), Mask); 7076 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 7077 DAG.getIntPtrConstant(0)); 7078 } else if (VT.getSizeInBits() == 64) { 7079 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b 7080 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught 7081 // to match extract_elt for f64. 7082 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7083 if (Idx == 0) 7084 return Op; 7085 7086 // UNPCKHPD the element to the lowest double word, then movsd. 7087 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored 7088 // to a f64mem, the whole operation is folded into a single MOVHPDmr. 7089 int Mask[2] = { 1, -1 }; 7090 EVT VVT = Op.getOperand(0).getValueType(); 7091 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 7092 DAG.getUNDEF(VVT), Mask); 7093 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 7094 DAG.getIntPtrConstant(0)); 7095 } 7096 7097 return SDValue(); 7098 } 7099 7100 SDValue 7101 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, 7102 SelectionDAG &DAG) const { 7103 EVT VT = Op.getValueType(); 7104 EVT EltVT = VT.getVectorElementType(); 7105 DebugLoc dl = Op.getDebugLoc(); 7106 7107 SDValue N0 = Op.getOperand(0); 7108 SDValue N1 = Op.getOperand(1); 7109 SDValue N2 = Op.getOperand(2); 7110 7111 if (VT.getSizeInBits() == 256) 7112 return SDValue(); 7113 7114 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) && 7115 isa<ConstantSDNode>(N2)) { 7116 unsigned Opc; 7117 if (VT == MVT::v8i16) 7118 Opc = X86ISD::PINSRW; 7119 else if (VT == MVT::v16i8) 7120 Opc = X86ISD::PINSRB; 7121 else 7122 Opc = X86ISD::PINSRB; 7123 7124 // Transform it so it match pinsr{b,w} which expects a GR32 as its second 7125 // argument. 7126 if (N1.getValueType() != MVT::i32) 7127 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7128 if (N2.getValueType() != MVT::i32) 7129 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7130 return DAG.getNode(Opc, dl, VT, N0, N1, N2); 7131 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) { 7132 // Bits [7:6] of the constant are the source select. This will always be 7133 // zero here. The DAG Combiner may combine an extract_elt index into these 7134 // bits. For example (insert (extract, 3), 2) could be matched by putting 7135 // the '3' into bits [7:6] of X86ISD::INSERTPS. 7136 // Bits [5:4] of the constant are the destination select. This is the 7137 // value of the incoming immediate. 7138 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may 7139 // combine either bitwise AND or insert of float 0.0 to set these bits. 7140 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4); 7141 // Create this as a scalar to vector.. 7142 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1); 7143 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2); 7144 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 7145 isa<ConstantSDNode>(N2)) { 7146 // PINSR* works with constant index. 7147 return Op; 7148 } 7149 return SDValue(); 7150 } 7151 7152 SDValue 7153 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 7154 EVT VT = Op.getValueType(); 7155 EVT EltVT = VT.getVectorElementType(); 7156 7157 DebugLoc dl = Op.getDebugLoc(); 7158 SDValue N0 = Op.getOperand(0); 7159 SDValue N1 = Op.getOperand(1); 7160 SDValue N2 = Op.getOperand(2); 7161 7162 // If this is a 256-bit vector result, first extract the 128-bit vector, 7163 // insert the element into the extracted half and then place it back. 7164 if (VT.getSizeInBits() == 256) { 7165 if (!isa<ConstantSDNode>(N2)) 7166 return SDValue(); 7167 7168 // Get the desired 128-bit vector half. 7169 unsigned NumElems = VT.getVectorNumElements(); 7170 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue(); 7171 bool Upper = IdxVal >= NumElems/2; 7172 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32); 7173 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl); 7174 7175 // Insert the element into the desired half. 7176 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, 7177 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2); 7178 7179 // Insert the changed part back to the 256-bit vector 7180 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl); 7181 } 7182 7183 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) 7184 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG); 7185 7186 if (EltVT == MVT::i8) 7187 return SDValue(); 7188 7189 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) { 7190 // Transform it so it match pinsrw which expects a 16-bit value in a GR32 7191 // as its second argument. 7192 if (N1.getValueType() != MVT::i32) 7193 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7194 if (N2.getValueType() != MVT::i32) 7195 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7196 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2); 7197 } 7198 return SDValue(); 7199 } 7200 7201 SDValue 7202 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const { 7203 LLVMContext *Context = DAG.getContext(); 7204 DebugLoc dl = Op.getDebugLoc(); 7205 EVT OpVT = Op.getValueType(); 7206 7207 // If this is a 256-bit vector result, first insert into a 128-bit 7208 // vector and then insert into the 256-bit vector. 7209 if (OpVT.getSizeInBits() > 128) { 7210 // Insert into a 128-bit vector. 7211 EVT VT128 = EVT::getVectorVT(*Context, 7212 OpVT.getVectorElementType(), 7213 OpVT.getVectorNumElements() / 2); 7214 7215 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0)); 7216 7217 // Insert the 128-bit vector. 7218 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op, 7219 DAG.getConstant(0, MVT::i32), 7220 DAG, dl); 7221 } 7222 7223 if (Op.getValueType() == MVT::v1i64 && 7224 Op.getOperand(0).getValueType() == MVT::i64) 7225 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0)); 7226 7227 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0)); 7228 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 && 7229 "Expected an SSE type!"); 7230 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), 7231 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt)); 7232 } 7233 7234 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in 7235 // a simple subregister reference or explicit instructions to grab 7236 // upper bits of a vector. 7237 SDValue 7238 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 7239 if (Subtarget->hasAVX()) { 7240 DebugLoc dl = Op.getNode()->getDebugLoc(); 7241 SDValue Vec = Op.getNode()->getOperand(0); 7242 SDValue Idx = Op.getNode()->getOperand(1); 7243 7244 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 7245 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) { 7246 return Extract128BitVector(Vec, Idx, DAG, dl); 7247 } 7248 } 7249 return SDValue(); 7250 } 7251 7252 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a 7253 // simple superregister reference or explicit instructions to insert 7254 // the upper bits of a vector. 7255 SDValue 7256 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 7257 if (Subtarget->hasAVX()) { 7258 DebugLoc dl = Op.getNode()->getDebugLoc(); 7259 SDValue Vec = Op.getNode()->getOperand(0); 7260 SDValue SubVec = Op.getNode()->getOperand(1); 7261 SDValue Idx = Op.getNode()->getOperand(2); 7262 7263 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 7264 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) { 7265 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl); 7266 } 7267 } 7268 return SDValue(); 7269 } 7270 7271 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 7272 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is 7273 // one of the above mentioned nodes. It has to be wrapped because otherwise 7274 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 7275 // be used to form addressing mode. These wrapped nodes will be selected 7276 // into MOV32ri. 7277 SDValue 7278 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { 7279 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 7280 7281 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7282 // global base reg. 7283 unsigned char OpFlag = 0; 7284 unsigned WrapperKind = X86ISD::Wrapper; 7285 CodeModel::Model M = getTargetMachine().getCodeModel(); 7286 7287 if (Subtarget->isPICStyleRIPRel() && 7288 (M == CodeModel::Small || M == CodeModel::Kernel)) 7289 WrapperKind = X86ISD::WrapperRIP; 7290 else if (Subtarget->isPICStyleGOT()) 7291 OpFlag = X86II::MO_GOTOFF; 7292 else if (Subtarget->isPICStyleStubPIC()) 7293 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7294 7295 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(), 7296 CP->getAlignment(), 7297 CP->getOffset(), OpFlag); 7298 DebugLoc DL = CP->getDebugLoc(); 7299 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7300 // With PIC, the address is actually $g + Offset. 7301 if (OpFlag) { 7302 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7303 DAG.getNode(X86ISD::GlobalBaseReg, 7304 DebugLoc(), getPointerTy()), 7305 Result); 7306 } 7307 7308 return Result; 7309 } 7310 7311 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 7312 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 7313 7314 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7315 // global base reg. 7316 unsigned char OpFlag = 0; 7317 unsigned WrapperKind = X86ISD::Wrapper; 7318 CodeModel::Model M = getTargetMachine().getCodeModel(); 7319 7320 if (Subtarget->isPICStyleRIPRel() && 7321 (M == CodeModel::Small || M == CodeModel::Kernel)) 7322 WrapperKind = X86ISD::WrapperRIP; 7323 else if (Subtarget->isPICStyleGOT()) 7324 OpFlag = X86II::MO_GOTOFF; 7325 else if (Subtarget->isPICStyleStubPIC()) 7326 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7327 7328 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(), 7329 OpFlag); 7330 DebugLoc DL = JT->getDebugLoc(); 7331 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7332 7333 // With PIC, the address is actually $g + Offset. 7334 if (OpFlag) 7335 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7336 DAG.getNode(X86ISD::GlobalBaseReg, 7337 DebugLoc(), getPointerTy()), 7338 Result); 7339 7340 return Result; 7341 } 7342 7343 SDValue 7344 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { 7345 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 7346 7347 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7348 // global base reg. 7349 unsigned char OpFlag = 0; 7350 unsigned WrapperKind = X86ISD::Wrapper; 7351 CodeModel::Model M = getTargetMachine().getCodeModel(); 7352 7353 if (Subtarget->isPICStyleRIPRel() && 7354 (M == CodeModel::Small || M == CodeModel::Kernel)) { 7355 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF()) 7356 OpFlag = X86II::MO_GOTPCREL; 7357 WrapperKind = X86ISD::WrapperRIP; 7358 } else if (Subtarget->isPICStyleGOT()) { 7359 OpFlag = X86II::MO_GOT; 7360 } else if (Subtarget->isPICStyleStubPIC()) { 7361 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE; 7362 } else if (Subtarget->isPICStyleStubNoDynamic()) { 7363 OpFlag = X86II::MO_DARWIN_NONLAZY; 7364 } 7365 7366 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag); 7367 7368 DebugLoc DL = Op.getDebugLoc(); 7369 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7370 7371 7372 // With PIC, the address is actually $g + Offset. 7373 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 7374 !Subtarget->is64Bit()) { 7375 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7376 DAG.getNode(X86ISD::GlobalBaseReg, 7377 DebugLoc(), getPointerTy()), 7378 Result); 7379 } 7380 7381 // For symbols that require a load from a stub to get the address, emit the 7382 // load. 7383 if (isGlobalStubReference(OpFlag)) 7384 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result, 7385 MachinePointerInfo::getGOT(), false, false, false, 0); 7386 7387 return Result; 7388 } 7389 7390 SDValue 7391 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { 7392 // Create the TargetBlockAddressAddress node. 7393 unsigned char OpFlags = 7394 Subtarget->ClassifyBlockAddressReference(); 7395 CodeModel::Model M = getTargetMachine().getCodeModel(); 7396 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 7397 DebugLoc dl = Op.getDebugLoc(); 7398 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), 7399 /*isTarget=*/true, OpFlags); 7400 7401 if (Subtarget->isPICStyleRIPRel() && 7402 (M == CodeModel::Small || M == CodeModel::Kernel)) 7403 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7404 else 7405 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7406 7407 // With PIC, the address is actually $g + Offset. 7408 if (isGlobalRelativeToPICBase(OpFlags)) { 7409 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7410 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7411 Result); 7412 } 7413 7414 return Result; 7415 } 7416 7417 SDValue 7418 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl, 7419 int64_t Offset, 7420 SelectionDAG &DAG) const { 7421 // Create the TargetGlobalAddress node, folding in the constant 7422 // offset if it is legal. 7423 unsigned char OpFlags = 7424 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 7425 CodeModel::Model M = getTargetMachine().getCodeModel(); 7426 SDValue Result; 7427 if (OpFlags == X86II::MO_NO_FLAG && 7428 X86::isOffsetSuitableForCodeModel(Offset, M)) { 7429 // A direct static reference to a global. 7430 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset); 7431 Offset = 0; 7432 } else { 7433 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 7434 } 7435 7436 if (Subtarget->isPICStyleRIPRel() && 7437 (M == CodeModel::Small || M == CodeModel::Kernel)) 7438 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7439 else 7440 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7441 7442 // With PIC, the address is actually $g + Offset. 7443 if (isGlobalRelativeToPICBase(OpFlags)) { 7444 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7445 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7446 Result); 7447 } 7448 7449 // For globals that require a load from a stub to get the address, emit the 7450 // load. 7451 if (isGlobalStubReference(OpFlags)) 7452 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result, 7453 MachinePointerInfo::getGOT(), false, false, false, 0); 7454 7455 // If there was a non-zero offset that we didn't fold, create an explicit 7456 // addition for it. 7457 if (Offset != 0) 7458 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result, 7459 DAG.getConstant(Offset, getPointerTy())); 7460 7461 return Result; 7462 } 7463 7464 SDValue 7465 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { 7466 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 7467 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 7468 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG); 7469 } 7470 7471 static SDValue 7472 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, 7473 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg, 7474 unsigned char OperandFlags) { 7475 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7476 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7477 DebugLoc dl = GA->getDebugLoc(); 7478 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7479 GA->getValueType(0), 7480 GA->getOffset(), 7481 OperandFlags); 7482 if (InFlag) { 7483 SDValue Ops[] = { Chain, TGA, *InFlag }; 7484 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3); 7485 } else { 7486 SDValue Ops[] = { Chain, TGA }; 7487 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2); 7488 } 7489 7490 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 7491 MFI->setAdjustsStack(true); 7492 7493 SDValue Flag = Chain.getValue(1); 7494 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag); 7495 } 7496 7497 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit 7498 static SDValue 7499 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7500 const EVT PtrVT) { 7501 SDValue InFlag; 7502 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better 7503 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 7504 DAG.getNode(X86ISD::GlobalBaseReg, 7505 DebugLoc(), PtrVT), InFlag); 7506 InFlag = Chain.getValue(1); 7507 7508 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD); 7509 } 7510 7511 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit 7512 static SDValue 7513 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7514 const EVT PtrVT) { 7515 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, 7516 X86::RAX, X86II::MO_TLSGD); 7517 } 7518 7519 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or 7520 // "local exec" model. 7521 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7522 const EVT PtrVT, TLSModel::Model model, 7523 bool is64Bit) { 7524 DebugLoc dl = GA->getDebugLoc(); 7525 7526 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit). 7527 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(), 7528 is64Bit ? 257 : 256)); 7529 7530 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 7531 DAG.getIntPtrConstant(0), 7532 MachinePointerInfo(Ptr), 7533 false, false, false, 0); 7534 7535 unsigned char OperandFlags = 0; 7536 // Most TLS accesses are not RIP relative, even on x86-64. One exception is 7537 // initialexec. 7538 unsigned WrapperKind = X86ISD::Wrapper; 7539 if (model == TLSModel::LocalExec) { 7540 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF; 7541 } else if (is64Bit) { 7542 assert(model == TLSModel::InitialExec); 7543 OperandFlags = X86II::MO_GOTTPOFF; 7544 WrapperKind = X86ISD::WrapperRIP; 7545 } else { 7546 assert(model == TLSModel::InitialExec); 7547 OperandFlags = X86II::MO_INDNTPOFF; 7548 } 7549 7550 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial 7551 // exec) 7552 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7553 GA->getValueType(0), 7554 GA->getOffset(), OperandFlags); 7555 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 7556 7557 if (model == TLSModel::InitialExec) 7558 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset, 7559 MachinePointerInfo::getGOT(), false, false, false, 0); 7560 7561 // The address of the thread local variable is the add of the thread 7562 // pointer with the offset of the variable. 7563 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 7564 } 7565 7566 SDValue 7567 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 7568 7569 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 7570 const GlobalValue *GV = GA->getGlobal(); 7571 7572 if (Subtarget->isTargetELF()) { 7573 // TODO: implement the "local dynamic" model 7574 // TODO: implement the "initial exec"model for pic executables 7575 7576 // If GV is an alias then use the aliasee for determining 7577 // thread-localness. 7578 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 7579 GV = GA->resolveAliasedGlobal(false); 7580 7581 TLSModel::Model model 7582 = getTLSModel(GV, getTargetMachine().getRelocationModel()); 7583 7584 switch (model) { 7585 case TLSModel::GeneralDynamic: 7586 case TLSModel::LocalDynamic: // not implemented 7587 if (Subtarget->is64Bit()) 7588 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy()); 7589 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy()); 7590 7591 case TLSModel::InitialExec: 7592 case TLSModel::LocalExec: 7593 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, 7594 Subtarget->is64Bit()); 7595 } 7596 } else if (Subtarget->isTargetDarwin()) { 7597 // Darwin only has one model of TLS. Lower to that. 7598 unsigned char OpFlag = 0; 7599 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ? 7600 X86ISD::WrapperRIP : X86ISD::Wrapper; 7601 7602 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7603 // global base reg. 7604 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) && 7605 !Subtarget->is64Bit(); 7606 if (PIC32) 7607 OpFlag = X86II::MO_TLVP_PIC_BASE; 7608 else 7609 OpFlag = X86II::MO_TLVP; 7610 DebugLoc DL = Op.getDebugLoc(); 7611 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 7612 GA->getValueType(0), 7613 GA->getOffset(), OpFlag); 7614 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7615 7616 // With PIC32, the address is actually $g + Offset. 7617 if (PIC32) 7618 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7619 DAG.getNode(X86ISD::GlobalBaseReg, 7620 DebugLoc(), getPointerTy()), 7621 Offset); 7622 7623 // Lowering the machine isd will make sure everything is in the right 7624 // location. 7625 SDValue Chain = DAG.getEntryNode(); 7626 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7627 SDValue Args[] = { Chain, Offset }; 7628 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2); 7629 7630 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls. 7631 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7632 MFI->setAdjustsStack(true); 7633 7634 // And our return value (tls address) is in the standard call return value 7635 // location. 7636 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 7637 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(), 7638 Chain.getValue(1)); 7639 } 7640 7641 assert(false && 7642 "TLS not implemented for this target."); 7643 7644 llvm_unreachable("Unreachable"); 7645 return SDValue(); 7646 } 7647 7648 7649 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and 7650 /// take a 2 x i32 value to shift plus a shift amount. 7651 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const { 7652 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7653 EVT VT = Op.getValueType(); 7654 unsigned VTBits = VT.getSizeInBits(); 7655 DebugLoc dl = Op.getDebugLoc(); 7656 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS; 7657 SDValue ShOpLo = Op.getOperand(0); 7658 SDValue ShOpHi = Op.getOperand(1); 7659 SDValue ShAmt = Op.getOperand(2); 7660 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7661 DAG.getConstant(VTBits - 1, MVT::i8)) 7662 : DAG.getConstant(0, VT); 7663 7664 SDValue Tmp2, Tmp3; 7665 if (Op.getOpcode() == ISD::SHL_PARTS) { 7666 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt); 7667 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 7668 } else { 7669 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt); 7670 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt); 7671 } 7672 7673 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt, 7674 DAG.getConstant(VTBits, MVT::i8)); 7675 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 7676 AndNode, DAG.getConstant(0, MVT::i8)); 7677 7678 SDValue Hi, Lo; 7679 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7680 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond }; 7681 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond }; 7682 7683 if (Op.getOpcode() == ISD::SHL_PARTS) { 7684 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7685 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7686 } else { 7687 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7688 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7689 } 7690 7691 SDValue Ops[2] = { Lo, Hi }; 7692 return DAG.getMergeValues(Ops, 2, dl); 7693 } 7694 7695 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, 7696 SelectionDAG &DAG) const { 7697 EVT SrcVT = Op.getOperand(0).getValueType(); 7698 7699 if (SrcVT.isVector()) 7700 return SDValue(); 7701 7702 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 && 7703 "Unknown SINT_TO_FP to lower!"); 7704 7705 // These are really Legal; return the operand so the caller accepts it as 7706 // Legal. 7707 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType())) 7708 return Op; 7709 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) && 7710 Subtarget->is64Bit()) { 7711 return Op; 7712 } 7713 7714 DebugLoc dl = Op.getDebugLoc(); 7715 unsigned Size = SrcVT.getSizeInBits()/8; 7716 MachineFunction &MF = DAG.getMachineFunction(); 7717 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false); 7718 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7719 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7720 StackSlot, 7721 MachinePointerInfo::getFixedStack(SSFI), 7722 false, false, 0); 7723 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG); 7724 } 7725 7726 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain, 7727 SDValue StackSlot, 7728 SelectionDAG &DAG) const { 7729 // Build the FILD 7730 DebugLoc DL = Op.getDebugLoc(); 7731 SDVTList Tys; 7732 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType()); 7733 if (useSSE) 7734 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue); 7735 else 7736 Tys = DAG.getVTList(Op.getValueType(), MVT::Other); 7737 7738 unsigned ByteSize = SrcVT.getSizeInBits()/8; 7739 7740 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot); 7741 MachineMemOperand *MMO; 7742 if (FI) { 7743 int SSFI = FI->getIndex(); 7744 MMO = 7745 DAG.getMachineFunction() 7746 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7747 MachineMemOperand::MOLoad, ByteSize, ByteSize); 7748 } else { 7749 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand(); 7750 StackSlot = StackSlot.getOperand(1); 7751 } 7752 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; 7753 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : 7754 X86ISD::FILD, DL, 7755 Tys, Ops, array_lengthof(Ops), 7756 SrcVT, MMO); 7757 7758 if (useSSE) { 7759 Chain = Result.getValue(1); 7760 SDValue InFlag = Result.getValue(2); 7761 7762 // FIXME: Currently the FST is flagged to the FILD_FLAG. This 7763 // shouldn't be necessary except that RFP cannot be live across 7764 // multiple blocks. When stackifier is fixed, they can be uncoupled. 7765 MachineFunction &MF = DAG.getMachineFunction(); 7766 unsigned SSFISize = Op.getValueType().getSizeInBits()/8; 7767 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false); 7768 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7769 Tys = DAG.getVTList(MVT::Other); 7770 SDValue Ops[] = { 7771 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag 7772 }; 7773 MachineMemOperand *MMO = 7774 DAG.getMachineFunction() 7775 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7776 MachineMemOperand::MOStore, SSFISize, SSFISize); 7777 7778 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, 7779 Ops, array_lengthof(Ops), 7780 Op.getValueType(), MMO); 7781 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot, 7782 MachinePointerInfo::getFixedStack(SSFI), 7783 false, false, false, 0); 7784 } 7785 7786 return Result; 7787 } 7788 7789 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion. 7790 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, 7791 SelectionDAG &DAG) const { 7792 // This algorithm is not obvious. Here it is in C code, more or less: 7793 /* 7794 double uint64_to_double( uint32_t hi, uint32_t lo ) { 7795 static const __m128i exp = { 0x4330000045300000ULL, 0 }; 7796 static const __m128d bias = { 0x1.0p84, 0x1.0p52 }; 7797 7798 // Copy ints to xmm registers. 7799 __m128i xh = _mm_cvtsi32_si128( hi ); 7800 __m128i xl = _mm_cvtsi32_si128( lo ); 7801 7802 // Combine into low half of a single xmm register. 7803 __m128i x = _mm_unpacklo_epi32( xh, xl ); 7804 __m128d d; 7805 double sd; 7806 7807 // Merge in appropriate exponents to give the integer bits the right 7808 // magnitude. 7809 x = _mm_unpacklo_epi32( x, exp ); 7810 7811 // Subtract away the biases to deal with the IEEE-754 double precision 7812 // implicit 1. 7813 d = _mm_sub_pd( (__m128d) x, bias ); 7814 7815 // All conversions up to here are exact. The correctly rounded result is 7816 // calculated using the current rounding mode using the following 7817 // horizontal add. 7818 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) ); 7819 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this 7820 // store doesn't really need to be here (except 7821 // maybe to zero the other double) 7822 return sd; 7823 } 7824 */ 7825 7826 DebugLoc dl = Op.getDebugLoc(); 7827 LLVMContext *Context = DAG.getContext(); 7828 7829 // Build some magic constants. 7830 std::vector<Constant*> CV0; 7831 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000))); 7832 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000))); 7833 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 7834 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 7835 Constant *C0 = ConstantVector::get(CV0); 7836 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16); 7837 7838 std::vector<Constant*> CV1; 7839 CV1.push_back( 7840 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL)))); 7841 CV1.push_back( 7842 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL)))); 7843 Constant *C1 = ConstantVector::get(CV1); 7844 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16); 7845 7846 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 7847 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7848 Op.getOperand(0), 7849 DAG.getIntPtrConstant(1))); 7850 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 7851 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7852 Op.getOperand(0), 7853 DAG.getIntPtrConstant(0))); 7854 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2); 7855 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0, 7856 MachinePointerInfo::getConstantPool(), 7857 false, false, false, 16); 7858 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0); 7859 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2); 7860 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1, 7861 MachinePointerInfo::getConstantPool(), 7862 false, false, false, 16); 7863 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1); 7864 7865 // Add the halves; easiest way is to swap them into another reg first. 7866 int ShufMask[2] = { 1, -1 }; 7867 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, 7868 DAG.getUNDEF(MVT::v2f64), ShufMask); 7869 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub); 7870 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add, 7871 DAG.getIntPtrConstant(0)); 7872 } 7873 7874 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion. 7875 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, 7876 SelectionDAG &DAG) const { 7877 DebugLoc dl = Op.getDebugLoc(); 7878 // FP constant to bias correct the final result. 7879 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 7880 MVT::f64); 7881 7882 // Load the 32-bit value into an XMM register. 7883 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 7884 Op.getOperand(0)); 7885 7886 // Zero out the upper parts of the register. 7887 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(), 7888 DAG); 7889 7890 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 7891 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load), 7892 DAG.getIntPtrConstant(0)); 7893 7894 // Or the load with the bias. 7895 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, 7896 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7897 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 7898 MVT::v2f64, Load)), 7899 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7900 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 7901 MVT::v2f64, Bias))); 7902 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 7903 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or), 7904 DAG.getIntPtrConstant(0)); 7905 7906 // Subtract the bias. 7907 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias); 7908 7909 // Handle final rounding. 7910 EVT DestVT = Op.getValueType(); 7911 7912 if (DestVT.bitsLT(MVT::f64)) { 7913 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 7914 DAG.getIntPtrConstant(0)); 7915 } else if (DestVT.bitsGT(MVT::f64)) { 7916 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 7917 } 7918 7919 // Handle final rounding. 7920 return Sub; 7921 } 7922 7923 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, 7924 SelectionDAG &DAG) const { 7925 SDValue N0 = Op.getOperand(0); 7926 DebugLoc dl = Op.getDebugLoc(); 7927 7928 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't 7929 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform 7930 // the optimization here. 7931 if (DAG.SignBitIsZero(N0)) 7932 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0); 7933 7934 EVT SrcVT = N0.getValueType(); 7935 EVT DstVT = Op.getValueType(); 7936 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64) 7937 return LowerUINT_TO_FP_i64(Op, DAG); 7938 else if (SrcVT == MVT::i32 && X86ScalarSSEf64) 7939 return LowerUINT_TO_FP_i32(Op, DAG); 7940 7941 // Make a 64-bit buffer, and use it to build an FILD. 7942 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64); 7943 if (SrcVT == MVT::i32) { 7944 SDValue WordOff = DAG.getConstant(4, getPointerTy()); 7945 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, 7946 getPointerTy(), StackSlot, WordOff); 7947 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7948 StackSlot, MachinePointerInfo(), 7949 false, false, 0); 7950 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32), 7951 OffsetSlot, MachinePointerInfo(), 7952 false, false, 0); 7953 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG); 7954 return Fild; 7955 } 7956 7957 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"); 7958 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7959 StackSlot, MachinePointerInfo(), 7960 false, false, 0); 7961 // For i64 source, we need to add the appropriate power of 2 if the input 7962 // was negative. This is the same as the optimization in 7963 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here, 7964 // we must be careful to do the computation in x87 extended precision, not 7965 // in SSE. (The generic code can't know it's OK to do this, or how to.) 7966 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 7967 MachineMemOperand *MMO = 7968 DAG.getMachineFunction() 7969 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7970 MachineMemOperand::MOLoad, 8, 8); 7971 7972 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other); 7973 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) }; 7974 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3, 7975 MVT::i64, MMO); 7976 7977 APInt FF(32, 0x5F800000ULL); 7978 7979 // Check whether the sign bit is set. 7980 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), 7981 Op.getOperand(0), DAG.getConstant(0, MVT::i64), 7982 ISD::SETLT); 7983 7984 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits. 7985 SDValue FudgePtr = DAG.getConstantPool( 7986 ConstantInt::get(*DAG.getContext(), FF.zext(64)), 7987 getPointerTy()); 7988 7989 // Get a pointer to FF if the sign bit was set, or to 0 otherwise. 7990 SDValue Zero = DAG.getIntPtrConstant(0); 7991 SDValue Four = DAG.getIntPtrConstant(4); 7992 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, 7993 Zero, Four); 7994 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset); 7995 7996 // Load the value out, extending it from f32 to f80. 7997 // FIXME: Avoid the extend by constructing the right constant pool? 7998 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), 7999 FudgePtr, MachinePointerInfo::getConstantPool(), 8000 MVT::f32, false, false, 4); 8001 // Extend everything to 80 bits to force it to be done on x87. 8002 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge); 8003 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0)); 8004 } 8005 8006 std::pair<SDValue,SDValue> X86TargetLowering:: 8007 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const { 8008 DebugLoc DL = Op.getDebugLoc(); 8009 8010 EVT DstTy = Op.getValueType(); 8011 8012 if (!IsSigned) { 8013 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT"); 8014 DstTy = MVT::i64; 8015 } 8016 8017 assert(DstTy.getSimpleVT() <= MVT::i64 && 8018 DstTy.getSimpleVT() >= MVT::i16 && 8019 "Unknown FP_TO_SINT to lower!"); 8020 8021 // These are really Legal. 8022 if (DstTy == MVT::i32 && 8023 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 8024 return std::make_pair(SDValue(), SDValue()); 8025 if (Subtarget->is64Bit() && 8026 DstTy == MVT::i64 && 8027 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 8028 return std::make_pair(SDValue(), SDValue()); 8029 8030 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary 8031 // stack slot. 8032 MachineFunction &MF = DAG.getMachineFunction(); 8033 unsigned MemSize = DstTy.getSizeInBits()/8; 8034 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 8035 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8036 8037 8038 8039 unsigned Opc; 8040 switch (DstTy.getSimpleVT().SimpleTy) { 8041 default: llvm_unreachable("Invalid FP_TO_SINT to lower!"); 8042 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break; 8043 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break; 8044 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break; 8045 } 8046 8047 SDValue Chain = DAG.getEntryNode(); 8048 SDValue Value = Op.getOperand(0); 8049 EVT TheVT = Op.getOperand(0).getValueType(); 8050 if (isScalarFPTypeInSSEReg(TheVT)) { 8051 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"); 8052 Chain = DAG.getStore(Chain, DL, Value, StackSlot, 8053 MachinePointerInfo::getFixedStack(SSFI), 8054 false, false, 0); 8055 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other); 8056 SDValue Ops[] = { 8057 Chain, StackSlot, DAG.getValueType(TheVT) 8058 }; 8059 8060 MachineMemOperand *MMO = 8061 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8062 MachineMemOperand::MOLoad, MemSize, MemSize); 8063 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3, 8064 DstTy, MMO); 8065 Chain = Value.getValue(1); 8066 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 8067 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8068 } 8069 8070 MachineMemOperand *MMO = 8071 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8072 MachineMemOperand::MOStore, MemSize, MemSize); 8073 8074 // Build the FP_TO_INT*_IN_MEM 8075 SDValue Ops[] = { Chain, Value, StackSlot }; 8076 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other), 8077 Ops, 3, DstTy, MMO); 8078 8079 return std::make_pair(FIST, StackSlot); 8080 } 8081 8082 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, 8083 SelectionDAG &DAG) const { 8084 if (Op.getValueType().isVector()) 8085 return SDValue(); 8086 8087 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true); 8088 SDValue FIST = Vals.first, StackSlot = Vals.second; 8089 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal. 8090 if (FIST.getNode() == 0) return Op; 8091 8092 // Load the result. 8093 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 8094 FIST, StackSlot, MachinePointerInfo(), 8095 false, false, false, 0); 8096 } 8097 8098 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, 8099 SelectionDAG &DAG) const { 8100 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false); 8101 SDValue FIST = Vals.first, StackSlot = Vals.second; 8102 assert(FIST.getNode() && "Unexpected failure"); 8103 8104 // Load the result. 8105 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 8106 FIST, StackSlot, MachinePointerInfo(), 8107 false, false, false, 0); 8108 } 8109 8110 SDValue X86TargetLowering::LowerFABS(SDValue Op, 8111 SelectionDAG &DAG) const { 8112 LLVMContext *Context = DAG.getContext(); 8113 DebugLoc dl = Op.getDebugLoc(); 8114 EVT VT = Op.getValueType(); 8115 EVT EltVT = VT; 8116 if (VT.isVector()) 8117 EltVT = VT.getVectorElementType(); 8118 std::vector<Constant*> CV; 8119 if (EltVT == MVT::f64) { 8120 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))); 8121 CV.push_back(C); 8122 CV.push_back(C); 8123 } else { 8124 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))); 8125 CV.push_back(C); 8126 CV.push_back(C); 8127 CV.push_back(C); 8128 CV.push_back(C); 8129 } 8130 Constant *C = ConstantVector::get(CV); 8131 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8132 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8133 MachinePointerInfo::getConstantPool(), 8134 false, false, false, 16); 8135 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask); 8136 } 8137 8138 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const { 8139 LLVMContext *Context = DAG.getContext(); 8140 DebugLoc dl = Op.getDebugLoc(); 8141 EVT VT = Op.getValueType(); 8142 EVT EltVT = VT; 8143 if (VT.isVector()) 8144 EltVT = VT.getVectorElementType(); 8145 std::vector<Constant*> CV; 8146 if (EltVT == MVT::f64) { 8147 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))); 8148 CV.push_back(C); 8149 CV.push_back(C); 8150 } else { 8151 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))); 8152 CV.push_back(C); 8153 CV.push_back(C); 8154 CV.push_back(C); 8155 CV.push_back(C); 8156 } 8157 Constant *C = ConstantVector::get(CV); 8158 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8159 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8160 MachinePointerInfo::getConstantPool(), 8161 false, false, false, 16); 8162 if (VT.isVector()) { 8163 return DAG.getNode(ISD::BITCAST, dl, VT, 8164 DAG.getNode(ISD::XOR, dl, MVT::v2i64, 8165 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 8166 Op.getOperand(0)), 8167 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask))); 8168 } else { 8169 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask); 8170 } 8171 } 8172 8173 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 8174 LLVMContext *Context = DAG.getContext(); 8175 SDValue Op0 = Op.getOperand(0); 8176 SDValue Op1 = Op.getOperand(1); 8177 DebugLoc dl = Op.getDebugLoc(); 8178 EVT VT = Op.getValueType(); 8179 EVT SrcVT = Op1.getValueType(); 8180 8181 // If second operand is smaller, extend it first. 8182 if (SrcVT.bitsLT(VT)) { 8183 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1); 8184 SrcVT = VT; 8185 } 8186 // And if it is bigger, shrink it first. 8187 if (SrcVT.bitsGT(VT)) { 8188 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1)); 8189 SrcVT = VT; 8190 } 8191 8192 // At this point the operands and the result should have the same 8193 // type, and that won't be f80 since that is not custom lowered. 8194 8195 // First get the sign bit of second operand. 8196 std::vector<Constant*> CV; 8197 if (SrcVT == MVT::f64) { 8198 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)))); 8199 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 8200 } else { 8201 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)))); 8202 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8203 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8204 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8205 } 8206 Constant *C = ConstantVector::get(CV); 8207 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8208 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx, 8209 MachinePointerInfo::getConstantPool(), 8210 false, false, false, 16); 8211 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1); 8212 8213 // Shift sign bit right or left if the two operands have different types. 8214 if (SrcVT.bitsGT(VT)) { 8215 // Op0 is MVT::f32, Op1 is MVT::f64. 8216 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit); 8217 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit, 8218 DAG.getConstant(32, MVT::i32)); 8219 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit); 8220 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit, 8221 DAG.getIntPtrConstant(0)); 8222 } 8223 8224 // Clear first operand sign bit. 8225 CV.clear(); 8226 if (VT == MVT::f64) { 8227 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))))); 8228 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 8229 } else { 8230 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))))); 8231 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8232 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8233 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8234 } 8235 C = ConstantVector::get(CV); 8236 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8237 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8238 MachinePointerInfo::getConstantPool(), 8239 false, false, false, 16); 8240 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2); 8241 8242 // Or the value with the sign bit. 8243 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit); 8244 } 8245 8246 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const { 8247 SDValue N0 = Op.getOperand(0); 8248 DebugLoc dl = Op.getDebugLoc(); 8249 EVT VT = Op.getValueType(); 8250 8251 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1). 8252 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0, 8253 DAG.getConstant(1, VT)); 8254 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT)); 8255 } 8256 8257 /// Emit nodes that will be selected as "test Op0,Op0", or something 8258 /// equivalent. 8259 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, 8260 SelectionDAG &DAG) const { 8261 DebugLoc dl = Op.getDebugLoc(); 8262 8263 // CF and OF aren't always set the way we want. Determine which 8264 // of these we need. 8265 bool NeedCF = false; 8266 bool NeedOF = false; 8267 switch (X86CC) { 8268 default: break; 8269 case X86::COND_A: case X86::COND_AE: 8270 case X86::COND_B: case X86::COND_BE: 8271 NeedCF = true; 8272 break; 8273 case X86::COND_G: case X86::COND_GE: 8274 case X86::COND_L: case X86::COND_LE: 8275 case X86::COND_O: case X86::COND_NO: 8276 NeedOF = true; 8277 break; 8278 } 8279 8280 // See if we can use the EFLAGS value from the operand instead of 8281 // doing a separate TEST. TEST always sets OF and CF to 0, so unless 8282 // we prove that the arithmetic won't overflow, we can't use OF or CF. 8283 if (Op.getResNo() != 0 || NeedOF || NeedCF) 8284 // Emit a CMP with 0, which is the TEST pattern. 8285 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 8286 DAG.getConstant(0, Op.getValueType())); 8287 8288 unsigned Opcode = 0; 8289 unsigned NumOperands = 0; 8290 switch (Op.getNode()->getOpcode()) { 8291 case ISD::ADD: 8292 // Due to an isel shortcoming, be conservative if this add is likely to be 8293 // selected as part of a load-modify-store instruction. When the root node 8294 // in a match is a store, isel doesn't know how to remap non-chain non-flag 8295 // uses of other nodes in the match, such as the ADD in this case. This 8296 // leads to the ADD being left around and reselected, with the result being 8297 // two adds in the output. Alas, even if none our users are stores, that 8298 // doesn't prove we're O.K. Ergo, if we have any parents that aren't 8299 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require 8300 // climbing the DAG back to the root, and it doesn't seem to be worth the 8301 // effort. 8302 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8303 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8304 if (UI->getOpcode() != ISD::CopyToReg && 8305 UI->getOpcode() != ISD::SETCC && 8306 UI->getOpcode() != ISD::STORE) 8307 goto default_case; 8308 8309 if (ConstantSDNode *C = 8310 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) { 8311 // An add of one will be selected as an INC. 8312 if (C->getAPIntValue() == 1) { 8313 Opcode = X86ISD::INC; 8314 NumOperands = 1; 8315 break; 8316 } 8317 8318 // An add of negative one (subtract of one) will be selected as a DEC. 8319 if (C->getAPIntValue().isAllOnesValue()) { 8320 Opcode = X86ISD::DEC; 8321 NumOperands = 1; 8322 break; 8323 } 8324 } 8325 8326 // Otherwise use a regular EFLAGS-setting add. 8327 Opcode = X86ISD::ADD; 8328 NumOperands = 2; 8329 break; 8330 case ISD::AND: { 8331 // If the primary and result isn't used, don't bother using X86ISD::AND, 8332 // because a TEST instruction will be better. 8333 bool NonFlagUse = false; 8334 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8335 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 8336 SDNode *User = *UI; 8337 unsigned UOpNo = UI.getOperandNo(); 8338 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) { 8339 // Look pass truncate. 8340 UOpNo = User->use_begin().getOperandNo(); 8341 User = *User->use_begin(); 8342 } 8343 8344 if (User->getOpcode() != ISD::BRCOND && 8345 User->getOpcode() != ISD::SETCC && 8346 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) { 8347 NonFlagUse = true; 8348 break; 8349 } 8350 } 8351 8352 if (!NonFlagUse) 8353 break; 8354 } 8355 // FALL THROUGH 8356 case ISD::SUB: 8357 case ISD::OR: 8358 case ISD::XOR: 8359 // Due to the ISEL shortcoming noted above, be conservative if this op is 8360 // likely to be selected as part of a load-modify-store instruction. 8361 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8362 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8363 if (UI->getOpcode() == ISD::STORE) 8364 goto default_case; 8365 8366 // Otherwise use a regular EFLAGS-setting instruction. 8367 switch (Op.getNode()->getOpcode()) { 8368 default: llvm_unreachable("unexpected operator!"); 8369 case ISD::SUB: Opcode = X86ISD::SUB; break; 8370 case ISD::OR: Opcode = X86ISD::OR; break; 8371 case ISD::XOR: Opcode = X86ISD::XOR; break; 8372 case ISD::AND: Opcode = X86ISD::AND; break; 8373 } 8374 8375 NumOperands = 2; 8376 break; 8377 case X86ISD::ADD: 8378 case X86ISD::SUB: 8379 case X86ISD::INC: 8380 case X86ISD::DEC: 8381 case X86ISD::OR: 8382 case X86ISD::XOR: 8383 case X86ISD::AND: 8384 return SDValue(Op.getNode(), 1); 8385 default: 8386 default_case: 8387 break; 8388 } 8389 8390 if (Opcode == 0) 8391 // Emit a CMP with 0, which is the TEST pattern. 8392 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 8393 DAG.getConstant(0, Op.getValueType())); 8394 8395 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 8396 SmallVector<SDValue, 4> Ops; 8397 for (unsigned i = 0; i != NumOperands; ++i) 8398 Ops.push_back(Op.getOperand(i)); 8399 8400 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands); 8401 DAG.ReplaceAllUsesWith(Op, New); 8402 return SDValue(New.getNode(), 1); 8403 } 8404 8405 /// Emit nodes that will be selected as "cmp Op0,Op1", or something 8406 /// equivalent. 8407 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC, 8408 SelectionDAG &DAG) const { 8409 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) 8410 if (C->getAPIntValue() == 0) 8411 return EmitTest(Op0, X86CC, DAG); 8412 8413 DebugLoc dl = Op0.getDebugLoc(); 8414 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1); 8415 } 8416 8417 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node 8418 /// if it's possible. 8419 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC, 8420 DebugLoc dl, SelectionDAG &DAG) const { 8421 SDValue Op0 = And.getOperand(0); 8422 SDValue Op1 = And.getOperand(1); 8423 if (Op0.getOpcode() == ISD::TRUNCATE) 8424 Op0 = Op0.getOperand(0); 8425 if (Op1.getOpcode() == ISD::TRUNCATE) 8426 Op1 = Op1.getOperand(0); 8427 8428 SDValue LHS, RHS; 8429 if (Op1.getOpcode() == ISD::SHL) 8430 std::swap(Op0, Op1); 8431 if (Op0.getOpcode() == ISD::SHL) { 8432 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0))) 8433 if (And00C->getZExtValue() == 1) { 8434 // If we looked past a truncate, check that it's only truncating away 8435 // known zeros. 8436 unsigned BitWidth = Op0.getValueSizeInBits(); 8437 unsigned AndBitWidth = And.getValueSizeInBits(); 8438 if (BitWidth > AndBitWidth) { 8439 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones; 8440 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones); 8441 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth) 8442 return SDValue(); 8443 } 8444 LHS = Op1; 8445 RHS = Op0.getOperand(1); 8446 } 8447 } else if (Op1.getOpcode() == ISD::Constant) { 8448 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1); 8449 SDValue AndLHS = Op0; 8450 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) { 8451 LHS = AndLHS.getOperand(0); 8452 RHS = AndLHS.getOperand(1); 8453 } 8454 } 8455 8456 if (LHS.getNode()) { 8457 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT 8458 // instruction. Since the shift amount is in-range-or-undefined, we know 8459 // that doing a bittest on the i32 value is ok. We extend to i32 because 8460 // the encoding for the i16 version is larger than the i32 version. 8461 // Also promote i16 to i32 for performance / code size reason. 8462 if (LHS.getValueType() == MVT::i8 || 8463 LHS.getValueType() == MVT::i16) 8464 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 8465 8466 // If the operand types disagree, extend the shift amount to match. Since 8467 // BT ignores high bits (like shifts) we can use anyextend. 8468 if (LHS.getValueType() != RHS.getValueType()) 8469 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS); 8470 8471 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS); 8472 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B; 8473 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8474 DAG.getConstant(Cond, MVT::i8), BT); 8475 } 8476 8477 return SDValue(); 8478 } 8479 8480 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 8481 8482 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG); 8483 8484 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer"); 8485 SDValue Op0 = Op.getOperand(0); 8486 SDValue Op1 = Op.getOperand(1); 8487 DebugLoc dl = Op.getDebugLoc(); 8488 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8489 8490 // Optimize to BT if possible. 8491 // Lower (X & (1 << N)) == 0 to BT(X, N). 8492 // Lower ((X >>u N) & 1) != 0 to BT(X, N). 8493 // Lower ((X >>s N) & 1) != 0 to BT(X, N). 8494 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && 8495 Op1.getOpcode() == ISD::Constant && 8496 cast<ConstantSDNode>(Op1)->isNullValue() && 8497 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 8498 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG); 8499 if (NewSetCC.getNode()) 8500 return NewSetCC; 8501 } 8502 8503 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of 8504 // these. 8505 if (Op1.getOpcode() == ISD::Constant && 8506 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 || 8507 cast<ConstantSDNode>(Op1)->isNullValue()) && 8508 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 8509 8510 // If the input is a setcc, then reuse the input setcc or use a new one with 8511 // the inverted condition. 8512 if (Op0.getOpcode() == X86ISD::SETCC) { 8513 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0); 8514 bool Invert = (CC == ISD::SETNE) ^ 8515 cast<ConstantSDNode>(Op1)->isNullValue(); 8516 if (!Invert) return Op0; 8517 8518 CCode = X86::GetOppositeBranchCondition(CCode); 8519 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8520 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1)); 8521 } 8522 } 8523 8524 bool isFP = Op1.getValueType().isFloatingPoint(); 8525 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 8526 if (X86CC == X86::COND_INVALID) 8527 return SDValue(); 8528 8529 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG); 8530 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8531 DAG.getConstant(X86CC, MVT::i8), EFLAGS); 8532 } 8533 8534 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128 8535 // ones, and then concatenate the result back. 8536 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) { 8537 EVT VT = Op.getValueType(); 8538 8539 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC && 8540 "Unsupported value type for operation"); 8541 8542 int NumElems = VT.getVectorNumElements(); 8543 DebugLoc dl = Op.getDebugLoc(); 8544 SDValue CC = Op.getOperand(2); 8545 SDValue Idx0 = DAG.getConstant(0, MVT::i32); 8546 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32); 8547 8548 // Extract the LHS vectors 8549 SDValue LHS = Op.getOperand(0); 8550 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl); 8551 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl); 8552 8553 // Extract the RHS vectors 8554 SDValue RHS = Op.getOperand(1); 8555 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl); 8556 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl); 8557 8558 // Issue the operation on the smaller types and concatenate the result back 8559 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 8560 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 8561 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 8562 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC), 8563 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC)); 8564 } 8565 8566 8567 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const { 8568 SDValue Cond; 8569 SDValue Op0 = Op.getOperand(0); 8570 SDValue Op1 = Op.getOperand(1); 8571 SDValue CC = Op.getOperand(2); 8572 EVT VT = Op.getValueType(); 8573 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 8574 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint(); 8575 DebugLoc dl = Op.getDebugLoc(); 8576 8577 if (isFP) { 8578 unsigned SSECC = 8; 8579 EVT EltVT = Op0.getValueType().getVectorElementType(); 8580 assert(EltVT == MVT::f32 || EltVT == MVT::f64); 8581 8582 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD; 8583 bool Swap = false; 8584 8585 // SSE Condition code mapping: 8586 // 0 - EQ 8587 // 1 - LT 8588 // 2 - LE 8589 // 3 - UNORD 8590 // 4 - NEQ 8591 // 5 - NLT 8592 // 6 - NLE 8593 // 7 - ORD 8594 switch (SetCCOpcode) { 8595 default: break; 8596 case ISD::SETOEQ: 8597 case ISD::SETEQ: SSECC = 0; break; 8598 case ISD::SETOGT: 8599 case ISD::SETGT: Swap = true; // Fallthrough 8600 case ISD::SETLT: 8601 case ISD::SETOLT: SSECC = 1; break; 8602 case ISD::SETOGE: 8603 case ISD::SETGE: Swap = true; // Fallthrough 8604 case ISD::SETLE: 8605 case ISD::SETOLE: SSECC = 2; break; 8606 case ISD::SETUO: SSECC = 3; break; 8607 case ISD::SETUNE: 8608 case ISD::SETNE: SSECC = 4; break; 8609 case ISD::SETULE: Swap = true; 8610 case ISD::SETUGE: SSECC = 5; break; 8611 case ISD::SETULT: Swap = true; 8612 case ISD::SETUGT: SSECC = 6; break; 8613 case ISD::SETO: SSECC = 7; break; 8614 } 8615 if (Swap) 8616 std::swap(Op0, Op1); 8617 8618 // In the two special cases we can't handle, emit two comparisons. 8619 if (SSECC == 8) { 8620 if (SetCCOpcode == ISD::SETUEQ) { 8621 SDValue UNORD, EQ; 8622 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8)); 8623 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8)); 8624 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ); 8625 } else if (SetCCOpcode == ISD::SETONE) { 8626 SDValue ORD, NEQ; 8627 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8)); 8628 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8)); 8629 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ); 8630 } 8631 llvm_unreachable("Illegal FP comparison"); 8632 } 8633 // Handle all other FP comparisons here. 8634 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8)); 8635 } 8636 8637 // Break 256-bit integer vector compare into smaller ones. 8638 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()) 8639 return Lower256IntVSETCC(Op, DAG); 8640 8641 // We are handling one of the integer comparisons here. Since SSE only has 8642 // GT and EQ comparisons for integer, swapping operands and multiple 8643 // operations may be required for some comparisons. 8644 unsigned Opc = 0, EQOpc = 0, GTOpc = 0; 8645 bool Swap = false, Invert = false, FlipSigns = false; 8646 8647 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 8648 default: break; 8649 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break; 8650 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break; 8651 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break; 8652 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break; 8653 } 8654 8655 switch (SetCCOpcode) { 8656 default: break; 8657 case ISD::SETNE: Invert = true; 8658 case ISD::SETEQ: Opc = EQOpc; break; 8659 case ISD::SETLT: Swap = true; 8660 case ISD::SETGT: Opc = GTOpc; break; 8661 case ISD::SETGE: Swap = true; 8662 case ISD::SETLE: Opc = GTOpc; Invert = true; break; 8663 case ISD::SETULT: Swap = true; 8664 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break; 8665 case ISD::SETUGE: Swap = true; 8666 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break; 8667 } 8668 if (Swap) 8669 std::swap(Op0, Op1); 8670 8671 // Check that the operation in question is available (most are plain SSE2, 8672 // but PCMPGTQ and PCMPEQQ have different requirements). 8673 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX()) 8674 return SDValue(); 8675 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX()) 8676 return SDValue(); 8677 8678 // Since SSE has no unsigned integer comparisons, we need to flip the sign 8679 // bits of the inputs before performing those operations. 8680 if (FlipSigns) { 8681 EVT EltVT = VT.getVectorElementType(); 8682 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), 8683 EltVT); 8684 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit); 8685 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0], 8686 SignBits.size()); 8687 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec); 8688 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec); 8689 } 8690 8691 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 8692 8693 // If the logical-not of the result is required, perform that now. 8694 if (Invert) 8695 Result = DAG.getNOT(dl, Result, VT); 8696 8697 return Result; 8698 } 8699 8700 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison. 8701 static bool isX86LogicalCmp(SDValue Op) { 8702 unsigned Opc = Op.getNode()->getOpcode(); 8703 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) 8704 return true; 8705 if (Op.getResNo() == 1 && 8706 (Opc == X86ISD::ADD || 8707 Opc == X86ISD::SUB || 8708 Opc == X86ISD::ADC || 8709 Opc == X86ISD::SBB || 8710 Opc == X86ISD::SMUL || 8711 Opc == X86ISD::UMUL || 8712 Opc == X86ISD::INC || 8713 Opc == X86ISD::DEC || 8714 Opc == X86ISD::OR || 8715 Opc == X86ISD::XOR || 8716 Opc == X86ISD::AND)) 8717 return true; 8718 8719 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL) 8720 return true; 8721 8722 return false; 8723 } 8724 8725 static bool isZero(SDValue V) { 8726 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 8727 return C && C->isNullValue(); 8728 } 8729 8730 static bool isAllOnes(SDValue V) { 8731 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 8732 return C && C->isAllOnesValue(); 8733 } 8734 8735 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8736 bool addTest = true; 8737 SDValue Cond = Op.getOperand(0); 8738 SDValue Op1 = Op.getOperand(1); 8739 SDValue Op2 = Op.getOperand(2); 8740 DebugLoc DL = Op.getDebugLoc(); 8741 SDValue CC; 8742 8743 if (Cond.getOpcode() == ISD::SETCC) { 8744 SDValue NewCond = LowerSETCC(Cond, DAG); 8745 if (NewCond.getNode()) 8746 Cond = NewCond; 8747 } 8748 8749 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y 8750 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y 8751 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y 8752 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y 8753 if (Cond.getOpcode() == X86ISD::SETCC && 8754 Cond.getOperand(1).getOpcode() == X86ISD::CMP && 8755 isZero(Cond.getOperand(1).getOperand(1))) { 8756 SDValue Cmp = Cond.getOperand(1); 8757 8758 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue(); 8759 8760 if ((isAllOnes(Op1) || isAllOnes(Op2)) && 8761 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) { 8762 SDValue Y = isAllOnes(Op2) ? Op1 : Op2; 8763 8764 SDValue CmpOp0 = Cmp.getOperand(0); 8765 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, 8766 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType())); 8767 8768 SDValue Res = // Res = 0 or -1. 8769 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 8770 DAG.getConstant(X86::COND_B, MVT::i8), Cmp); 8771 8772 if (isAllOnes(Op1) != (CondCode == X86::COND_E)) 8773 Res = DAG.getNOT(DL, Res, Res.getValueType()); 8774 8775 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2); 8776 if (N2C == 0 || !N2C->isNullValue()) 8777 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y); 8778 return Res; 8779 } 8780 } 8781 8782 // Look past (and (setcc_carry (cmp ...)), 1). 8783 if (Cond.getOpcode() == ISD::AND && 8784 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 8785 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 8786 if (C && C->getAPIntValue() == 1) 8787 Cond = Cond.getOperand(0); 8788 } 8789 8790 // If condition flag is set by a X86ISD::CMP, then use it as the condition 8791 // setting operand in place of the X86ISD::SETCC. 8792 unsigned CondOpcode = Cond.getOpcode(); 8793 if (CondOpcode == X86ISD::SETCC || 8794 CondOpcode == X86ISD::SETCC_CARRY) { 8795 CC = Cond.getOperand(0); 8796 8797 SDValue Cmp = Cond.getOperand(1); 8798 unsigned Opc = Cmp.getOpcode(); 8799 EVT VT = Op.getValueType(); 8800 8801 bool IllegalFPCMov = false; 8802 if (VT.isFloatingPoint() && !VT.isVector() && 8803 !isScalarFPTypeInSSEReg(VT)) // FPStack? 8804 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue()); 8805 8806 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || 8807 Opc == X86ISD::BT) { // FIXME 8808 Cond = Cmp; 8809 addTest = false; 8810 } 8811 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 8812 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 8813 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 8814 Cond.getOperand(0).getValueType() != MVT::i8)) { 8815 SDValue LHS = Cond.getOperand(0); 8816 SDValue RHS = Cond.getOperand(1); 8817 unsigned X86Opcode; 8818 unsigned X86Cond; 8819 SDVTList VTs; 8820 switch (CondOpcode) { 8821 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 8822 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 8823 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 8824 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 8825 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 8826 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 8827 default: llvm_unreachable("unexpected overflowing operator"); 8828 } 8829 if (CondOpcode == ISD::UMULO) 8830 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 8831 MVT::i32); 8832 else 8833 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 8834 8835 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS); 8836 8837 if (CondOpcode == ISD::UMULO) 8838 Cond = X86Op.getValue(2); 8839 else 8840 Cond = X86Op.getValue(1); 8841 8842 CC = DAG.getConstant(X86Cond, MVT::i8); 8843 addTest = false; 8844 } 8845 8846 if (addTest) { 8847 // Look pass the truncate. 8848 if (Cond.getOpcode() == ISD::TRUNCATE) 8849 Cond = Cond.getOperand(0); 8850 8851 // We know the result of AND is compared against zero. Try to match 8852 // it to BT. 8853 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 8854 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG); 8855 if (NewSetCC.getNode()) { 8856 CC = NewSetCC.getOperand(0); 8857 Cond = NewSetCC.getOperand(1); 8858 addTest = false; 8859 } 8860 } 8861 } 8862 8863 if (addTest) { 8864 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 8865 Cond = EmitTest(Cond, X86::COND_NE, DAG); 8866 } 8867 8868 // a < b ? -1 : 0 -> RES = ~setcc_carry 8869 // a < b ? 0 : -1 -> RES = setcc_carry 8870 // a >= b ? -1 : 0 -> RES = setcc_carry 8871 // a >= b ? 0 : -1 -> RES = ~setcc_carry 8872 if (Cond.getOpcode() == X86ISD::CMP) { 8873 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue(); 8874 8875 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) && 8876 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) { 8877 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 8878 DAG.getConstant(X86::COND_B, MVT::i8), Cond); 8879 if (isAllOnes(Op1) != (CondCode == X86::COND_B)) 8880 return DAG.getNOT(DL, Res, Res.getValueType()); 8881 return Res; 8882 } 8883 } 8884 8885 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if 8886 // condition is true. 8887 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 8888 SDValue Ops[] = { Op2, Op1, CC, Cond }; 8889 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops)); 8890 } 8891 8892 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or 8893 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart 8894 // from the AND / OR. 8895 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) { 8896 Opc = Op.getOpcode(); 8897 if (Opc != ISD::OR && Opc != ISD::AND) 8898 return false; 8899 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC && 8900 Op.getOperand(0).hasOneUse() && 8901 Op.getOperand(1).getOpcode() == X86ISD::SETCC && 8902 Op.getOperand(1).hasOneUse()); 8903 } 8904 8905 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and 8906 // 1 and that the SETCC node has a single use. 8907 static bool isXor1OfSetCC(SDValue Op) { 8908 if (Op.getOpcode() != ISD::XOR) 8909 return false; 8910 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8911 if (N1C && N1C->getAPIntValue() == 1) { 8912 return Op.getOperand(0).getOpcode() == X86ISD::SETCC && 8913 Op.getOperand(0).hasOneUse(); 8914 } 8915 return false; 8916 } 8917 8918 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 8919 bool addTest = true; 8920 SDValue Chain = Op.getOperand(0); 8921 SDValue Cond = Op.getOperand(1); 8922 SDValue Dest = Op.getOperand(2); 8923 DebugLoc dl = Op.getDebugLoc(); 8924 SDValue CC; 8925 bool Inverted = false; 8926 8927 if (Cond.getOpcode() == ISD::SETCC) { 8928 // Check for setcc([su]{add,sub,mul}o == 0). 8929 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ && 8930 isa<ConstantSDNode>(Cond.getOperand(1)) && 8931 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() && 8932 Cond.getOperand(0).getResNo() == 1 && 8933 (Cond.getOperand(0).getOpcode() == ISD::SADDO || 8934 Cond.getOperand(0).getOpcode() == ISD::UADDO || 8935 Cond.getOperand(0).getOpcode() == ISD::SSUBO || 8936 Cond.getOperand(0).getOpcode() == ISD::USUBO || 8937 Cond.getOperand(0).getOpcode() == ISD::SMULO || 8938 Cond.getOperand(0).getOpcode() == ISD::UMULO)) { 8939 Inverted = true; 8940 Cond = Cond.getOperand(0); 8941 } else { 8942 SDValue NewCond = LowerSETCC(Cond, DAG); 8943 if (NewCond.getNode()) 8944 Cond = NewCond; 8945 } 8946 } 8947 #if 0 8948 // FIXME: LowerXALUO doesn't handle these!! 8949 else if (Cond.getOpcode() == X86ISD::ADD || 8950 Cond.getOpcode() == X86ISD::SUB || 8951 Cond.getOpcode() == X86ISD::SMUL || 8952 Cond.getOpcode() == X86ISD::UMUL) 8953 Cond = LowerXALUO(Cond, DAG); 8954 #endif 8955 8956 // Look pass (and (setcc_carry (cmp ...)), 1). 8957 if (Cond.getOpcode() == ISD::AND && 8958 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 8959 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 8960 if (C && C->getAPIntValue() == 1) 8961 Cond = Cond.getOperand(0); 8962 } 8963 8964 // If condition flag is set by a X86ISD::CMP, then use it as the condition 8965 // setting operand in place of the X86ISD::SETCC. 8966 unsigned CondOpcode = Cond.getOpcode(); 8967 if (CondOpcode == X86ISD::SETCC || 8968 CondOpcode == X86ISD::SETCC_CARRY) { 8969 CC = Cond.getOperand(0); 8970 8971 SDValue Cmp = Cond.getOperand(1); 8972 unsigned Opc = Cmp.getOpcode(); 8973 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp?? 8974 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) { 8975 Cond = Cmp; 8976 addTest = false; 8977 } else { 8978 switch (cast<ConstantSDNode>(CC)->getZExtValue()) { 8979 default: break; 8980 case X86::COND_O: 8981 case X86::COND_B: 8982 // These can only come from an arithmetic instruction with overflow, 8983 // e.g. SADDO, UADDO. 8984 Cond = Cond.getNode()->getOperand(1); 8985 addTest = false; 8986 break; 8987 } 8988 } 8989 } 8990 CondOpcode = Cond.getOpcode(); 8991 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 8992 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 8993 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 8994 Cond.getOperand(0).getValueType() != MVT::i8)) { 8995 SDValue LHS = Cond.getOperand(0); 8996 SDValue RHS = Cond.getOperand(1); 8997 unsigned X86Opcode; 8998 unsigned X86Cond; 8999 SDVTList VTs; 9000 switch (CondOpcode) { 9001 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 9002 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 9003 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 9004 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 9005 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 9006 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 9007 default: llvm_unreachable("unexpected overflowing operator"); 9008 } 9009 if (Inverted) 9010 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond); 9011 if (CondOpcode == ISD::UMULO) 9012 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 9013 MVT::i32); 9014 else 9015 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 9016 9017 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS); 9018 9019 if (CondOpcode == ISD::UMULO) 9020 Cond = X86Op.getValue(2); 9021 else 9022 Cond = X86Op.getValue(1); 9023 9024 CC = DAG.getConstant(X86Cond, MVT::i8); 9025 addTest = false; 9026 } else { 9027 unsigned CondOpc; 9028 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) { 9029 SDValue Cmp = Cond.getOperand(0).getOperand(1); 9030 if (CondOpc == ISD::OR) { 9031 // Also, recognize the pattern generated by an FCMP_UNE. We can emit 9032 // two branches instead of an explicit OR instruction with a 9033 // separate test. 9034 if (Cmp == Cond.getOperand(1).getOperand(1) && 9035 isX86LogicalCmp(Cmp)) { 9036 CC = Cond.getOperand(0).getOperand(0); 9037 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9038 Chain, Dest, CC, Cmp); 9039 CC = Cond.getOperand(1).getOperand(0); 9040 Cond = Cmp; 9041 addTest = false; 9042 } 9043 } else { // ISD::AND 9044 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit 9045 // two branches instead of an explicit AND instruction with a 9046 // separate test. However, we only do this if this block doesn't 9047 // have a fall-through edge, because this requires an explicit 9048 // jmp when the condition is false. 9049 if (Cmp == Cond.getOperand(1).getOperand(1) && 9050 isX86LogicalCmp(Cmp) && 9051 Op.getNode()->hasOneUse()) { 9052 X86::CondCode CCode = 9053 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 9054 CCode = X86::GetOppositeBranchCondition(CCode); 9055 CC = DAG.getConstant(CCode, MVT::i8); 9056 SDNode *User = *Op.getNode()->use_begin(); 9057 // Look for an unconditional branch following this conditional branch. 9058 // We need this because we need to reverse the successors in order 9059 // to implement FCMP_OEQ. 9060 if (User->getOpcode() == ISD::BR) { 9061 SDValue FalseBB = User->getOperand(1); 9062 SDNode *NewBR = 9063 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9064 assert(NewBR == User); 9065 (void)NewBR; 9066 Dest = FalseBB; 9067 9068 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9069 Chain, Dest, CC, Cmp); 9070 X86::CondCode CCode = 9071 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0); 9072 CCode = X86::GetOppositeBranchCondition(CCode); 9073 CC = DAG.getConstant(CCode, MVT::i8); 9074 Cond = Cmp; 9075 addTest = false; 9076 } 9077 } 9078 } 9079 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) { 9080 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition. 9081 // It should be transformed during dag combiner except when the condition 9082 // is set by a arithmetics with overflow node. 9083 X86::CondCode CCode = 9084 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 9085 CCode = X86::GetOppositeBranchCondition(CCode); 9086 CC = DAG.getConstant(CCode, MVT::i8); 9087 Cond = Cond.getOperand(0).getOperand(1); 9088 addTest = false; 9089 } else if (Cond.getOpcode() == ISD::SETCC && 9090 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) { 9091 // For FCMP_OEQ, we can emit 9092 // two branches instead of an explicit AND instruction with a 9093 // separate test. However, we only do this if this block doesn't 9094 // have a fall-through edge, because this requires an explicit 9095 // jmp when the condition is false. 9096 if (Op.getNode()->hasOneUse()) { 9097 SDNode *User = *Op.getNode()->use_begin(); 9098 // Look for an unconditional branch following this conditional branch. 9099 // We need this because we need to reverse the successors in order 9100 // to implement FCMP_OEQ. 9101 if (User->getOpcode() == ISD::BR) { 9102 SDValue FalseBB = User->getOperand(1); 9103 SDNode *NewBR = 9104 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9105 assert(NewBR == User); 9106 (void)NewBR; 9107 Dest = FalseBB; 9108 9109 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 9110 Cond.getOperand(0), Cond.getOperand(1)); 9111 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9112 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9113 Chain, Dest, CC, Cmp); 9114 CC = DAG.getConstant(X86::COND_P, MVT::i8); 9115 Cond = Cmp; 9116 addTest = false; 9117 } 9118 } 9119 } else if (Cond.getOpcode() == ISD::SETCC && 9120 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) { 9121 // For FCMP_UNE, we can emit 9122 // two branches instead of an explicit AND instruction with a 9123 // separate test. However, we only do this if this block doesn't 9124 // have a fall-through edge, because this requires an explicit 9125 // jmp when the condition is false. 9126 if (Op.getNode()->hasOneUse()) { 9127 SDNode *User = *Op.getNode()->use_begin(); 9128 // Look for an unconditional branch following this conditional branch. 9129 // We need this because we need to reverse the successors in order 9130 // to implement FCMP_UNE. 9131 if (User->getOpcode() == ISD::BR) { 9132 SDValue FalseBB = User->getOperand(1); 9133 SDNode *NewBR = 9134 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9135 assert(NewBR == User); 9136 (void)NewBR; 9137 9138 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 9139 Cond.getOperand(0), Cond.getOperand(1)); 9140 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9141 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9142 Chain, Dest, CC, Cmp); 9143 CC = DAG.getConstant(X86::COND_NP, MVT::i8); 9144 Cond = Cmp; 9145 addTest = false; 9146 Dest = FalseBB; 9147 } 9148 } 9149 } 9150 } 9151 9152 if (addTest) { 9153 // Look pass the truncate. 9154 if (Cond.getOpcode() == ISD::TRUNCATE) 9155 Cond = Cond.getOperand(0); 9156 9157 // We know the result of AND is compared against zero. Try to match 9158 // it to BT. 9159 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 9160 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG); 9161 if (NewSetCC.getNode()) { 9162 CC = NewSetCC.getOperand(0); 9163 Cond = NewSetCC.getOperand(1); 9164 addTest = false; 9165 } 9166 } 9167 } 9168 9169 if (addTest) { 9170 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9171 Cond = EmitTest(Cond, X86::COND_NE, DAG); 9172 } 9173 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9174 Chain, Dest, CC, Cond); 9175 } 9176 9177 9178 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets. 9179 // Calls to _alloca is needed to probe the stack when allocating more than 4k 9180 // bytes in one go. Touching the stack at 4K increments is necessary to ensure 9181 // that the guard pages used by the OS virtual memory manager are allocated in 9182 // correct sequence. 9183 SDValue 9184 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 9185 SelectionDAG &DAG) const { 9186 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() || 9187 EnableSegmentedStacks) && 9188 "This should be used only on Windows targets or when segmented stacks " 9189 "are being used"); 9190 assert(!Subtarget->isTargetEnvMacho() && "Not implemented"); 9191 DebugLoc dl = Op.getDebugLoc(); 9192 9193 // Get the inputs. 9194 SDValue Chain = Op.getOperand(0); 9195 SDValue Size = Op.getOperand(1); 9196 // FIXME: Ensure alignment here 9197 9198 bool Is64Bit = Subtarget->is64Bit(); 9199 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32; 9200 9201 if (EnableSegmentedStacks) { 9202 MachineFunction &MF = DAG.getMachineFunction(); 9203 MachineRegisterInfo &MRI = MF.getRegInfo(); 9204 9205 if (Is64Bit) { 9206 // The 64 bit implementation of segmented stacks needs to clobber both r10 9207 // r11. This makes it impossible to use it along with nested parameters. 9208 const Function *F = MF.getFunction(); 9209 9210 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 9211 I != E; I++) 9212 if (I->hasNestAttr()) 9213 report_fatal_error("Cannot use segmented stacks with functions that " 9214 "have nested arguments."); 9215 } 9216 9217 const TargetRegisterClass *AddrRegClass = 9218 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32); 9219 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass); 9220 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size); 9221 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain, 9222 DAG.getRegister(Vreg, SPTy)); 9223 SDValue Ops1[2] = { Value, Chain }; 9224 return DAG.getMergeValues(Ops1, 2, dl); 9225 } else { 9226 SDValue Flag; 9227 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX); 9228 9229 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag); 9230 Flag = Chain.getValue(1); 9231 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9232 9233 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag); 9234 Flag = Chain.getValue(1); 9235 9236 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1); 9237 9238 SDValue Ops1[2] = { Chain.getValue(0), Chain }; 9239 return DAG.getMergeValues(Ops1, 2, dl); 9240 } 9241 } 9242 9243 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 9244 MachineFunction &MF = DAG.getMachineFunction(); 9245 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 9246 9247 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 9248 DebugLoc DL = Op.getDebugLoc(); 9249 9250 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) { 9251 // vastart just stores the address of the VarArgsFrameIndex slot into the 9252 // memory location argument. 9253 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 9254 getPointerTy()); 9255 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 9256 MachinePointerInfo(SV), false, false, 0); 9257 } 9258 9259 // __va_list_tag: 9260 // gp_offset (0 - 6 * 8) 9261 // fp_offset (48 - 48 + 8 * 16) 9262 // overflow_arg_area (point to parameters coming in memory). 9263 // reg_save_area 9264 SmallVector<SDValue, 8> MemOps; 9265 SDValue FIN = Op.getOperand(1); 9266 // Store gp_offset 9267 SDValue Store = DAG.getStore(Op.getOperand(0), DL, 9268 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), 9269 MVT::i32), 9270 FIN, MachinePointerInfo(SV), false, false, 0); 9271 MemOps.push_back(Store); 9272 9273 // Store fp_offset 9274 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9275 FIN, DAG.getIntPtrConstant(4)); 9276 Store = DAG.getStore(Op.getOperand(0), DL, 9277 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), 9278 MVT::i32), 9279 FIN, MachinePointerInfo(SV, 4), false, false, 0); 9280 MemOps.push_back(Store); 9281 9282 // Store ptr to overflow_arg_area 9283 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9284 FIN, DAG.getIntPtrConstant(4)); 9285 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 9286 getPointerTy()); 9287 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, 9288 MachinePointerInfo(SV, 8), 9289 false, false, 0); 9290 MemOps.push_back(Store); 9291 9292 // Store ptr to reg_save_area. 9293 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9294 FIN, DAG.getIntPtrConstant(8)); 9295 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 9296 getPointerTy()); 9297 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, 9298 MachinePointerInfo(SV, 16), false, false, 0); 9299 MemOps.push_back(Store); 9300 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 9301 &MemOps[0], MemOps.size()); 9302 } 9303 9304 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 9305 assert(Subtarget->is64Bit() && 9306 "LowerVAARG only handles 64-bit va_arg!"); 9307 assert((Subtarget->isTargetLinux() || 9308 Subtarget->isTargetDarwin()) && 9309 "Unhandled target in LowerVAARG"); 9310 assert(Op.getNode()->getNumOperands() == 4); 9311 SDValue Chain = Op.getOperand(0); 9312 SDValue SrcPtr = Op.getOperand(1); 9313 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 9314 unsigned Align = Op.getConstantOperandVal(3); 9315 DebugLoc dl = Op.getDebugLoc(); 9316 9317 EVT ArgVT = Op.getNode()->getValueType(0); 9318 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 9319 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy); 9320 uint8_t ArgMode; 9321 9322 // Decide which area this value should be read from. 9323 // TODO: Implement the AMD64 ABI in its entirety. This simple 9324 // selection mechanism works only for the basic types. 9325 if (ArgVT == MVT::f80) { 9326 llvm_unreachable("va_arg for f80 not yet implemented"); 9327 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) { 9328 ArgMode = 2; // Argument passed in XMM register. Use fp_offset. 9329 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) { 9330 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset. 9331 } else { 9332 llvm_unreachable("Unhandled argument type in LowerVAARG"); 9333 } 9334 9335 if (ArgMode == 2) { 9336 // Sanity Check: Make sure using fp_offset makes sense. 9337 assert(!UseSoftFloat && 9338 !(DAG.getMachineFunction() 9339 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) && 9340 Subtarget->hasXMM()); 9341 } 9342 9343 // Insert VAARG_64 node into the DAG 9344 // VAARG_64 returns two values: Variable Argument Address, Chain 9345 SmallVector<SDValue, 11> InstOps; 9346 InstOps.push_back(Chain); 9347 InstOps.push_back(SrcPtr); 9348 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32)); 9349 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8)); 9350 InstOps.push_back(DAG.getConstant(Align, MVT::i32)); 9351 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other); 9352 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl, 9353 VTs, &InstOps[0], InstOps.size(), 9354 MVT::i64, 9355 MachinePointerInfo(SV), 9356 /*Align=*/0, 9357 /*Volatile=*/false, 9358 /*ReadMem=*/true, 9359 /*WriteMem=*/true); 9360 Chain = VAARG.getValue(1); 9361 9362 // Load the next argument and return it 9363 return DAG.getLoad(ArgVT, dl, 9364 Chain, 9365 VAARG, 9366 MachinePointerInfo(), 9367 false, false, false, 0); 9368 } 9369 9370 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 9371 // X86-64 va_list is a struct { i32, i32, i8*, i8* }. 9372 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!"); 9373 SDValue Chain = Op.getOperand(0); 9374 SDValue DstPtr = Op.getOperand(1); 9375 SDValue SrcPtr = Op.getOperand(2); 9376 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 9377 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 9378 DebugLoc DL = Op.getDebugLoc(); 9379 9380 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, 9381 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false, 9382 false, 9383 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 9384 } 9385 9386 SDValue 9387 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const { 9388 DebugLoc dl = Op.getDebugLoc(); 9389 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9390 switch (IntNo) { 9391 default: return SDValue(); // Don't custom lower most intrinsics. 9392 // Comparison intrinsics. 9393 case Intrinsic::x86_sse_comieq_ss: 9394 case Intrinsic::x86_sse_comilt_ss: 9395 case Intrinsic::x86_sse_comile_ss: 9396 case Intrinsic::x86_sse_comigt_ss: 9397 case Intrinsic::x86_sse_comige_ss: 9398 case Intrinsic::x86_sse_comineq_ss: 9399 case Intrinsic::x86_sse_ucomieq_ss: 9400 case Intrinsic::x86_sse_ucomilt_ss: 9401 case Intrinsic::x86_sse_ucomile_ss: 9402 case Intrinsic::x86_sse_ucomigt_ss: 9403 case Intrinsic::x86_sse_ucomige_ss: 9404 case Intrinsic::x86_sse_ucomineq_ss: 9405 case Intrinsic::x86_sse2_comieq_sd: 9406 case Intrinsic::x86_sse2_comilt_sd: 9407 case Intrinsic::x86_sse2_comile_sd: 9408 case Intrinsic::x86_sse2_comigt_sd: 9409 case Intrinsic::x86_sse2_comige_sd: 9410 case Intrinsic::x86_sse2_comineq_sd: 9411 case Intrinsic::x86_sse2_ucomieq_sd: 9412 case Intrinsic::x86_sse2_ucomilt_sd: 9413 case Intrinsic::x86_sse2_ucomile_sd: 9414 case Intrinsic::x86_sse2_ucomigt_sd: 9415 case Intrinsic::x86_sse2_ucomige_sd: 9416 case Intrinsic::x86_sse2_ucomineq_sd: { 9417 unsigned Opc = 0; 9418 ISD::CondCode CC = ISD::SETCC_INVALID; 9419 switch (IntNo) { 9420 default: break; 9421 case Intrinsic::x86_sse_comieq_ss: 9422 case Intrinsic::x86_sse2_comieq_sd: 9423 Opc = X86ISD::COMI; 9424 CC = ISD::SETEQ; 9425 break; 9426 case Intrinsic::x86_sse_comilt_ss: 9427 case Intrinsic::x86_sse2_comilt_sd: 9428 Opc = X86ISD::COMI; 9429 CC = ISD::SETLT; 9430 break; 9431 case Intrinsic::x86_sse_comile_ss: 9432 case Intrinsic::x86_sse2_comile_sd: 9433 Opc = X86ISD::COMI; 9434 CC = ISD::SETLE; 9435 break; 9436 case Intrinsic::x86_sse_comigt_ss: 9437 case Intrinsic::x86_sse2_comigt_sd: 9438 Opc = X86ISD::COMI; 9439 CC = ISD::SETGT; 9440 break; 9441 case Intrinsic::x86_sse_comige_ss: 9442 case Intrinsic::x86_sse2_comige_sd: 9443 Opc = X86ISD::COMI; 9444 CC = ISD::SETGE; 9445 break; 9446 case Intrinsic::x86_sse_comineq_ss: 9447 case Intrinsic::x86_sse2_comineq_sd: 9448 Opc = X86ISD::COMI; 9449 CC = ISD::SETNE; 9450 break; 9451 case Intrinsic::x86_sse_ucomieq_ss: 9452 case Intrinsic::x86_sse2_ucomieq_sd: 9453 Opc = X86ISD::UCOMI; 9454 CC = ISD::SETEQ; 9455 break; 9456 case Intrinsic::x86_sse_ucomilt_ss: 9457 case Intrinsic::x86_sse2_ucomilt_sd: 9458 Opc = X86ISD::UCOMI; 9459 CC = ISD::SETLT; 9460 break; 9461 case Intrinsic::x86_sse_ucomile_ss: 9462 case Intrinsic::x86_sse2_ucomile_sd: 9463 Opc = X86ISD::UCOMI; 9464 CC = ISD::SETLE; 9465 break; 9466 case Intrinsic::x86_sse_ucomigt_ss: 9467 case Intrinsic::x86_sse2_ucomigt_sd: 9468 Opc = X86ISD::UCOMI; 9469 CC = ISD::SETGT; 9470 break; 9471 case Intrinsic::x86_sse_ucomige_ss: 9472 case Intrinsic::x86_sse2_ucomige_sd: 9473 Opc = X86ISD::UCOMI; 9474 CC = ISD::SETGE; 9475 break; 9476 case Intrinsic::x86_sse_ucomineq_ss: 9477 case Intrinsic::x86_sse2_ucomineq_sd: 9478 Opc = X86ISD::UCOMI; 9479 CC = ISD::SETNE; 9480 break; 9481 } 9482 9483 SDValue LHS = Op.getOperand(1); 9484 SDValue RHS = Op.getOperand(2); 9485 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG); 9486 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!"); 9487 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS); 9488 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9489 DAG.getConstant(X86CC, MVT::i8), Cond); 9490 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 9491 } 9492 // Arithmetic intrinsics. 9493 case Intrinsic::x86_sse3_hadd_ps: 9494 case Intrinsic::x86_sse3_hadd_pd: 9495 case Intrinsic::x86_avx_hadd_ps_256: 9496 case Intrinsic::x86_avx_hadd_pd_256: 9497 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(), 9498 Op.getOperand(1), Op.getOperand(2)); 9499 case Intrinsic::x86_sse3_hsub_ps: 9500 case Intrinsic::x86_sse3_hsub_pd: 9501 case Intrinsic::x86_avx_hsub_ps_256: 9502 case Intrinsic::x86_avx_hsub_pd_256: 9503 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(), 9504 Op.getOperand(1), Op.getOperand(2)); 9505 // ptest and testp intrinsics. The intrinsic these come from are designed to 9506 // return an integer value, not just an instruction so lower it to the ptest 9507 // or testp pattern and a setcc for the result. 9508 case Intrinsic::x86_sse41_ptestz: 9509 case Intrinsic::x86_sse41_ptestc: 9510 case Intrinsic::x86_sse41_ptestnzc: 9511 case Intrinsic::x86_avx_ptestz_256: 9512 case Intrinsic::x86_avx_ptestc_256: 9513 case Intrinsic::x86_avx_ptestnzc_256: 9514 case Intrinsic::x86_avx_vtestz_ps: 9515 case Intrinsic::x86_avx_vtestc_ps: 9516 case Intrinsic::x86_avx_vtestnzc_ps: 9517 case Intrinsic::x86_avx_vtestz_pd: 9518 case Intrinsic::x86_avx_vtestc_pd: 9519 case Intrinsic::x86_avx_vtestnzc_pd: 9520 case Intrinsic::x86_avx_vtestz_ps_256: 9521 case Intrinsic::x86_avx_vtestc_ps_256: 9522 case Intrinsic::x86_avx_vtestnzc_ps_256: 9523 case Intrinsic::x86_avx_vtestz_pd_256: 9524 case Intrinsic::x86_avx_vtestc_pd_256: 9525 case Intrinsic::x86_avx_vtestnzc_pd_256: { 9526 bool IsTestPacked = false; 9527 unsigned X86CC = 0; 9528 switch (IntNo) { 9529 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering."); 9530 case Intrinsic::x86_avx_vtestz_ps: 9531 case Intrinsic::x86_avx_vtestz_pd: 9532 case Intrinsic::x86_avx_vtestz_ps_256: 9533 case Intrinsic::x86_avx_vtestz_pd_256: 9534 IsTestPacked = true; // Fallthrough 9535 case Intrinsic::x86_sse41_ptestz: 9536 case Intrinsic::x86_avx_ptestz_256: 9537 // ZF = 1 9538 X86CC = X86::COND_E; 9539 break; 9540 case Intrinsic::x86_avx_vtestc_ps: 9541 case Intrinsic::x86_avx_vtestc_pd: 9542 case Intrinsic::x86_avx_vtestc_ps_256: 9543 case Intrinsic::x86_avx_vtestc_pd_256: 9544 IsTestPacked = true; // Fallthrough 9545 case Intrinsic::x86_sse41_ptestc: 9546 case Intrinsic::x86_avx_ptestc_256: 9547 // CF = 1 9548 X86CC = X86::COND_B; 9549 break; 9550 case Intrinsic::x86_avx_vtestnzc_ps: 9551 case Intrinsic::x86_avx_vtestnzc_pd: 9552 case Intrinsic::x86_avx_vtestnzc_ps_256: 9553 case Intrinsic::x86_avx_vtestnzc_pd_256: 9554 IsTestPacked = true; // Fallthrough 9555 case Intrinsic::x86_sse41_ptestnzc: 9556 case Intrinsic::x86_avx_ptestnzc_256: 9557 // ZF and CF = 0 9558 X86CC = X86::COND_A; 9559 break; 9560 } 9561 9562 SDValue LHS = Op.getOperand(1); 9563 SDValue RHS = Op.getOperand(2); 9564 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST; 9565 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS); 9566 SDValue CC = DAG.getConstant(X86CC, MVT::i8); 9567 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test); 9568 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 9569 } 9570 9571 // Fix vector shift instructions where the last operand is a non-immediate 9572 // i32 value. 9573 case Intrinsic::x86_avx2_pslli_w: 9574 case Intrinsic::x86_avx2_pslli_d: 9575 case Intrinsic::x86_avx2_pslli_q: 9576 case Intrinsic::x86_avx2_psrli_w: 9577 case Intrinsic::x86_avx2_psrli_d: 9578 case Intrinsic::x86_avx2_psrli_q: 9579 case Intrinsic::x86_avx2_psrai_w: 9580 case Intrinsic::x86_avx2_psrai_d: 9581 case Intrinsic::x86_sse2_pslli_w: 9582 case Intrinsic::x86_sse2_pslli_d: 9583 case Intrinsic::x86_sse2_pslli_q: 9584 case Intrinsic::x86_sse2_psrli_w: 9585 case Intrinsic::x86_sse2_psrli_d: 9586 case Intrinsic::x86_sse2_psrli_q: 9587 case Intrinsic::x86_sse2_psrai_w: 9588 case Intrinsic::x86_sse2_psrai_d: 9589 case Intrinsic::x86_mmx_pslli_w: 9590 case Intrinsic::x86_mmx_pslli_d: 9591 case Intrinsic::x86_mmx_pslli_q: 9592 case Intrinsic::x86_mmx_psrli_w: 9593 case Intrinsic::x86_mmx_psrli_d: 9594 case Intrinsic::x86_mmx_psrli_q: 9595 case Intrinsic::x86_mmx_psrai_w: 9596 case Intrinsic::x86_mmx_psrai_d: { 9597 SDValue ShAmt = Op.getOperand(2); 9598 if (isa<ConstantSDNode>(ShAmt)) 9599 return SDValue(); 9600 9601 unsigned NewIntNo = 0; 9602 EVT ShAmtVT = MVT::v4i32; 9603 switch (IntNo) { 9604 case Intrinsic::x86_sse2_pslli_w: 9605 NewIntNo = Intrinsic::x86_sse2_psll_w; 9606 break; 9607 case Intrinsic::x86_sse2_pslli_d: 9608 NewIntNo = Intrinsic::x86_sse2_psll_d; 9609 break; 9610 case Intrinsic::x86_sse2_pslli_q: 9611 NewIntNo = Intrinsic::x86_sse2_psll_q; 9612 break; 9613 case Intrinsic::x86_sse2_psrli_w: 9614 NewIntNo = Intrinsic::x86_sse2_psrl_w; 9615 break; 9616 case Intrinsic::x86_sse2_psrli_d: 9617 NewIntNo = Intrinsic::x86_sse2_psrl_d; 9618 break; 9619 case Intrinsic::x86_sse2_psrli_q: 9620 NewIntNo = Intrinsic::x86_sse2_psrl_q; 9621 break; 9622 case Intrinsic::x86_sse2_psrai_w: 9623 NewIntNo = Intrinsic::x86_sse2_psra_w; 9624 break; 9625 case Intrinsic::x86_sse2_psrai_d: 9626 NewIntNo = Intrinsic::x86_sse2_psra_d; 9627 break; 9628 case Intrinsic::x86_avx2_pslli_w: 9629 NewIntNo = Intrinsic::x86_avx2_psll_w; 9630 break; 9631 case Intrinsic::x86_avx2_pslli_d: 9632 NewIntNo = Intrinsic::x86_avx2_psll_d; 9633 break; 9634 case Intrinsic::x86_avx2_pslli_q: 9635 NewIntNo = Intrinsic::x86_avx2_psll_q; 9636 break; 9637 case Intrinsic::x86_avx2_psrli_w: 9638 NewIntNo = Intrinsic::x86_avx2_psrl_w; 9639 break; 9640 case Intrinsic::x86_avx2_psrli_d: 9641 NewIntNo = Intrinsic::x86_avx2_psrl_d; 9642 break; 9643 case Intrinsic::x86_avx2_psrli_q: 9644 NewIntNo = Intrinsic::x86_avx2_psrl_q; 9645 break; 9646 case Intrinsic::x86_avx2_psrai_w: 9647 NewIntNo = Intrinsic::x86_avx2_psra_w; 9648 break; 9649 case Intrinsic::x86_avx2_psrai_d: 9650 NewIntNo = Intrinsic::x86_avx2_psra_d; 9651 break; 9652 default: { 9653 ShAmtVT = MVT::v2i32; 9654 switch (IntNo) { 9655 case Intrinsic::x86_mmx_pslli_w: 9656 NewIntNo = Intrinsic::x86_mmx_psll_w; 9657 break; 9658 case Intrinsic::x86_mmx_pslli_d: 9659 NewIntNo = Intrinsic::x86_mmx_psll_d; 9660 break; 9661 case Intrinsic::x86_mmx_pslli_q: 9662 NewIntNo = Intrinsic::x86_mmx_psll_q; 9663 break; 9664 case Intrinsic::x86_mmx_psrli_w: 9665 NewIntNo = Intrinsic::x86_mmx_psrl_w; 9666 break; 9667 case Intrinsic::x86_mmx_psrli_d: 9668 NewIntNo = Intrinsic::x86_mmx_psrl_d; 9669 break; 9670 case Intrinsic::x86_mmx_psrli_q: 9671 NewIntNo = Intrinsic::x86_mmx_psrl_q; 9672 break; 9673 case Intrinsic::x86_mmx_psrai_w: 9674 NewIntNo = Intrinsic::x86_mmx_psra_w; 9675 break; 9676 case Intrinsic::x86_mmx_psrai_d: 9677 NewIntNo = Intrinsic::x86_mmx_psra_d; 9678 break; 9679 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 9680 } 9681 break; 9682 } 9683 } 9684 9685 // The vector shift intrinsics with scalars uses 32b shift amounts but 9686 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 9687 // to be zero. 9688 SDValue ShOps[4]; 9689 ShOps[0] = ShAmt; 9690 ShOps[1] = DAG.getConstant(0, MVT::i32); 9691 if (ShAmtVT == MVT::v4i32) { 9692 ShOps[2] = DAG.getUNDEF(MVT::i32); 9693 ShOps[3] = DAG.getUNDEF(MVT::i32); 9694 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4); 9695 } else { 9696 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2); 9697 // FIXME this must be lowered to get rid of the invalid type. 9698 } 9699 9700 EVT VT = Op.getValueType(); 9701 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt); 9702 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9703 DAG.getConstant(NewIntNo, MVT::i32), 9704 Op.getOperand(1), ShAmt); 9705 } 9706 } 9707 } 9708 9709 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, 9710 SelectionDAG &DAG) const { 9711 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 9712 MFI->setReturnAddressIsTaken(true); 9713 9714 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9715 DebugLoc dl = Op.getDebugLoc(); 9716 9717 if (Depth > 0) { 9718 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 9719 SDValue Offset = 9720 DAG.getConstant(TD->getPointerSize(), 9721 Subtarget->is64Bit() ? MVT::i64 : MVT::i32); 9722 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 9723 DAG.getNode(ISD::ADD, dl, getPointerTy(), 9724 FrameAddr, Offset), 9725 MachinePointerInfo(), false, false, false, 0); 9726 } 9727 9728 // Just load the return address. 9729 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); 9730 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 9731 RetAddrFI, MachinePointerInfo(), false, false, false, 0); 9732 } 9733 9734 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 9735 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 9736 MFI->setFrameAddressIsTaken(true); 9737 9738 EVT VT = Op.getValueType(); 9739 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful 9740 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9741 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP; 9742 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 9743 while (Depth--) 9744 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 9745 MachinePointerInfo(), 9746 false, false, false, 0); 9747 return FrameAddr; 9748 } 9749 9750 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op, 9751 SelectionDAG &DAG) const { 9752 return DAG.getIntPtrConstant(2*TD->getPointerSize()); 9753 } 9754 9755 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const { 9756 MachineFunction &MF = DAG.getMachineFunction(); 9757 SDValue Chain = Op.getOperand(0); 9758 SDValue Offset = Op.getOperand(1); 9759 SDValue Handler = Op.getOperand(2); 9760 DebugLoc dl = Op.getDebugLoc(); 9761 9762 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, 9763 Subtarget->is64Bit() ? X86::RBP : X86::EBP, 9764 getPointerTy()); 9765 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX); 9766 9767 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame, 9768 DAG.getIntPtrConstant(TD->getPointerSize())); 9769 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset); 9770 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(), 9771 false, false, 0); 9772 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr); 9773 MF.getRegInfo().addLiveOut(StoreAddrReg); 9774 9775 return DAG.getNode(X86ISD::EH_RETURN, dl, 9776 MVT::Other, 9777 Chain, DAG.getRegister(StoreAddrReg, getPointerTy())); 9778 } 9779 9780 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 9781 SelectionDAG &DAG) const { 9782 return Op.getOperand(0); 9783 } 9784 9785 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 9786 SelectionDAG &DAG) const { 9787 SDValue Root = Op.getOperand(0); 9788 SDValue Trmp = Op.getOperand(1); // trampoline 9789 SDValue FPtr = Op.getOperand(2); // nested function 9790 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 9791 DebugLoc dl = Op.getDebugLoc(); 9792 9793 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 9794 9795 if (Subtarget->is64Bit()) { 9796 SDValue OutChains[6]; 9797 9798 // Large code-model. 9799 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode. 9800 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode. 9801 9802 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10); 9803 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11); 9804 9805 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix 9806 9807 // Load the pointer to the nested function into R11. 9808 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11 9809 SDValue Addr = Trmp; 9810 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 9811 Addr, MachinePointerInfo(TrmpAddr), 9812 false, false, 0); 9813 9814 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9815 DAG.getConstant(2, MVT::i64)); 9816 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, 9817 MachinePointerInfo(TrmpAddr, 2), 9818 false, false, 2); 9819 9820 // Load the 'nest' parameter value into R10. 9821 // R10 is specified in X86CallingConv.td 9822 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10 9823 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9824 DAG.getConstant(10, MVT::i64)); 9825 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 9826 Addr, MachinePointerInfo(TrmpAddr, 10), 9827 false, false, 0); 9828 9829 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9830 DAG.getConstant(12, MVT::i64)); 9831 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, 9832 MachinePointerInfo(TrmpAddr, 12), 9833 false, false, 2); 9834 9835 // Jump to the nested function. 9836 OpCode = (JMP64r << 8) | REX_WB; // jmpq *... 9837 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9838 DAG.getConstant(20, MVT::i64)); 9839 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 9840 Addr, MachinePointerInfo(TrmpAddr, 20), 9841 false, false, 0); 9842 9843 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11 9844 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9845 DAG.getConstant(22, MVT::i64)); 9846 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr, 9847 MachinePointerInfo(TrmpAddr, 22), 9848 false, false, 0); 9849 9850 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6); 9851 } else { 9852 const Function *Func = 9853 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue()); 9854 CallingConv::ID CC = Func->getCallingConv(); 9855 unsigned NestReg; 9856 9857 switch (CC) { 9858 default: 9859 llvm_unreachable("Unsupported calling convention"); 9860 case CallingConv::C: 9861 case CallingConv::X86_StdCall: { 9862 // Pass 'nest' parameter in ECX. 9863 // Must be kept in sync with X86CallingConv.td 9864 NestReg = X86::ECX; 9865 9866 // Check that ECX wasn't needed by an 'inreg' parameter. 9867 FunctionType *FTy = Func->getFunctionType(); 9868 const AttrListPtr &Attrs = Func->getAttributes(); 9869 9870 if (!Attrs.isEmpty() && !Func->isVarArg()) { 9871 unsigned InRegCount = 0; 9872 unsigned Idx = 1; 9873 9874 for (FunctionType::param_iterator I = FTy->param_begin(), 9875 E = FTy->param_end(); I != E; ++I, ++Idx) 9876 if (Attrs.paramHasAttr(Idx, Attribute::InReg)) 9877 // FIXME: should only count parameters that are lowered to integers. 9878 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32; 9879 9880 if (InRegCount > 2) { 9881 report_fatal_error("Nest register in use - reduce number of inreg" 9882 " parameters!"); 9883 } 9884 } 9885 break; 9886 } 9887 case CallingConv::X86_FastCall: 9888 case CallingConv::X86_ThisCall: 9889 case CallingConv::Fast: 9890 // Pass 'nest' parameter in EAX. 9891 // Must be kept in sync with X86CallingConv.td 9892 NestReg = X86::EAX; 9893 break; 9894 } 9895 9896 SDValue OutChains[4]; 9897 SDValue Addr, Disp; 9898 9899 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9900 DAG.getConstant(10, MVT::i32)); 9901 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr); 9902 9903 // This is storing the opcode for MOV32ri. 9904 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte. 9905 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg); 9906 OutChains[0] = DAG.getStore(Root, dl, 9907 DAG.getConstant(MOV32ri|N86Reg, MVT::i8), 9908 Trmp, MachinePointerInfo(TrmpAddr), 9909 false, false, 0); 9910 9911 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9912 DAG.getConstant(1, MVT::i32)); 9913 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, 9914 MachinePointerInfo(TrmpAddr, 1), 9915 false, false, 1); 9916 9917 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode. 9918 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9919 DAG.getConstant(5, MVT::i32)); 9920 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr, 9921 MachinePointerInfo(TrmpAddr, 5), 9922 false, false, 1); 9923 9924 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9925 DAG.getConstant(6, MVT::i32)); 9926 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, 9927 MachinePointerInfo(TrmpAddr, 6), 9928 false, false, 1); 9929 9930 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4); 9931 } 9932 } 9933 9934 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 9935 SelectionDAG &DAG) const { 9936 /* 9937 The rounding mode is in bits 11:10 of FPSR, and has the following 9938 settings: 9939 00 Round to nearest 9940 01 Round to -inf 9941 10 Round to +inf 9942 11 Round to 0 9943 9944 FLT_ROUNDS, on the other hand, expects the following: 9945 -1 Undefined 9946 0 Round to 0 9947 1 Round to nearest 9948 2 Round to +inf 9949 3 Round to -inf 9950 9951 To perform the conversion, we do: 9952 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3) 9953 */ 9954 9955 MachineFunction &MF = DAG.getMachineFunction(); 9956 const TargetMachine &TM = MF.getTarget(); 9957 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 9958 unsigned StackAlignment = TFI.getStackAlignment(); 9959 EVT VT = Op.getValueType(); 9960 DebugLoc DL = Op.getDebugLoc(); 9961 9962 // Save FP Control Word to stack slot 9963 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false); 9964 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 9965 9966 9967 MachineMemOperand *MMO = 9968 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 9969 MachineMemOperand::MOStore, 2, 2); 9970 9971 SDValue Ops[] = { DAG.getEntryNode(), StackSlot }; 9972 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL, 9973 DAG.getVTList(MVT::Other), 9974 Ops, 2, MVT::i16, MMO); 9975 9976 // Load FP Control Word from stack slot 9977 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, 9978 MachinePointerInfo(), false, false, false, 0); 9979 9980 // Transform as necessary 9981 SDValue CWD1 = 9982 DAG.getNode(ISD::SRL, DL, MVT::i16, 9983 DAG.getNode(ISD::AND, DL, MVT::i16, 9984 CWD, DAG.getConstant(0x800, MVT::i16)), 9985 DAG.getConstant(11, MVT::i8)); 9986 SDValue CWD2 = 9987 DAG.getNode(ISD::SRL, DL, MVT::i16, 9988 DAG.getNode(ISD::AND, DL, MVT::i16, 9989 CWD, DAG.getConstant(0x400, MVT::i16)), 9990 DAG.getConstant(9, MVT::i8)); 9991 9992 SDValue RetVal = 9993 DAG.getNode(ISD::AND, DL, MVT::i16, 9994 DAG.getNode(ISD::ADD, DL, MVT::i16, 9995 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2), 9996 DAG.getConstant(1, MVT::i16)), 9997 DAG.getConstant(3, MVT::i16)); 9998 9999 10000 return DAG.getNode((VT.getSizeInBits() < 16 ? 10001 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal); 10002 } 10003 10004 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const { 10005 EVT VT = Op.getValueType(); 10006 EVT OpVT = VT; 10007 unsigned NumBits = VT.getSizeInBits(); 10008 DebugLoc dl = Op.getDebugLoc(); 10009 10010 Op = Op.getOperand(0); 10011 if (VT == MVT::i8) { 10012 // Zero extend to i32 since there is not an i8 bsr. 10013 OpVT = MVT::i32; 10014 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 10015 } 10016 10017 // Issue a bsr (scan bits in reverse) which also sets EFLAGS. 10018 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 10019 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 10020 10021 // If src is zero (i.e. bsr sets ZF), returns NumBits. 10022 SDValue Ops[] = { 10023 Op, 10024 DAG.getConstant(NumBits+NumBits-1, OpVT), 10025 DAG.getConstant(X86::COND_E, MVT::i8), 10026 Op.getValue(1) 10027 }; 10028 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 10029 10030 // Finally xor with NumBits-1. 10031 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 10032 10033 if (VT == MVT::i8) 10034 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 10035 return Op; 10036 } 10037 10038 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const { 10039 EVT VT = Op.getValueType(); 10040 EVT OpVT = VT; 10041 unsigned NumBits = VT.getSizeInBits(); 10042 DebugLoc dl = Op.getDebugLoc(); 10043 10044 Op = Op.getOperand(0); 10045 if (VT == MVT::i8) { 10046 OpVT = MVT::i32; 10047 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 10048 } 10049 10050 // Issue a bsf (scan bits forward) which also sets EFLAGS. 10051 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 10052 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); 10053 10054 // If src is zero (i.e. bsf sets ZF), returns NumBits. 10055 SDValue Ops[] = { 10056 Op, 10057 DAG.getConstant(NumBits, OpVT), 10058 DAG.getConstant(X86::COND_E, MVT::i8), 10059 Op.getValue(1) 10060 }; 10061 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 10062 10063 if (VT == MVT::i8) 10064 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 10065 return Op; 10066 } 10067 10068 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit 10069 // ones, and then concatenate the result back. 10070 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) { 10071 EVT VT = Op.getValueType(); 10072 10073 assert(VT.getSizeInBits() == 256 && VT.isInteger() && 10074 "Unsupported value type for operation"); 10075 10076 int NumElems = VT.getVectorNumElements(); 10077 DebugLoc dl = Op.getDebugLoc(); 10078 SDValue Idx0 = DAG.getConstant(0, MVT::i32); 10079 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32); 10080 10081 // Extract the LHS vectors 10082 SDValue LHS = Op.getOperand(0); 10083 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl); 10084 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl); 10085 10086 // Extract the RHS vectors 10087 SDValue RHS = Op.getOperand(1); 10088 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl); 10089 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl); 10090 10091 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10092 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 10093 10094 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 10095 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1), 10096 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2)); 10097 } 10098 10099 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const { 10100 assert(Op.getValueType().getSizeInBits() == 256 && 10101 Op.getValueType().isInteger() && 10102 "Only handle AVX 256-bit vector integer operation"); 10103 return Lower256IntArith(Op, DAG); 10104 } 10105 10106 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const { 10107 assert(Op.getValueType().getSizeInBits() == 256 && 10108 Op.getValueType().isInteger() && 10109 "Only handle AVX 256-bit vector integer operation"); 10110 return Lower256IntArith(Op, DAG); 10111 } 10112 10113 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10114 EVT VT = Op.getValueType(); 10115 10116 // Decompose 256-bit ops into smaller 128-bit ops. 10117 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()) 10118 return Lower256IntArith(Op, DAG); 10119 10120 DebugLoc dl = Op.getDebugLoc(); 10121 10122 SDValue A = Op.getOperand(0); 10123 SDValue B = Op.getOperand(1); 10124 10125 if (VT == MVT::v4i64) { 10126 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2"); 10127 10128 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32); 10129 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32); 10130 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b ); 10131 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi ); 10132 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b ); 10133 // 10134 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 ); 10135 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 ); 10136 // return AloBlo + AloBhi + AhiBlo; 10137 10138 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10139 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32), 10140 A, DAG.getConstant(32, MVT::i32)); 10141 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10142 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32), 10143 B, DAG.getConstant(32, MVT::i32)); 10144 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10145 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32), 10146 A, B); 10147 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10148 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32), 10149 A, Bhi); 10150 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10151 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32), 10152 Ahi, B); 10153 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10154 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32), 10155 AloBhi, DAG.getConstant(32, MVT::i32)); 10156 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10157 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32), 10158 AhiBlo, DAG.getConstant(32, MVT::i32)); 10159 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 10160 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 10161 return Res; 10162 } 10163 10164 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply"); 10165 10166 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32); 10167 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32); 10168 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b ); 10169 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi ); 10170 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b ); 10171 // 10172 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 ); 10173 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 ); 10174 // return AloBlo + AloBhi + AhiBlo; 10175 10176 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10177 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 10178 A, DAG.getConstant(32, MVT::i32)); 10179 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10180 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 10181 B, DAG.getConstant(32, MVT::i32)); 10182 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10183 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 10184 A, B); 10185 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10186 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 10187 A, Bhi); 10188 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10189 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 10190 Ahi, B); 10191 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10192 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 10193 AloBhi, DAG.getConstant(32, MVT::i32)); 10194 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10195 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 10196 AhiBlo, DAG.getConstant(32, MVT::i32)); 10197 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 10198 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 10199 return Res; 10200 } 10201 10202 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const { 10203 10204 EVT VT = Op.getValueType(); 10205 DebugLoc dl = Op.getDebugLoc(); 10206 SDValue R = Op.getOperand(0); 10207 SDValue Amt = Op.getOperand(1); 10208 LLVMContext *Context = DAG.getContext(); 10209 10210 if (!Subtarget->hasXMMInt()) 10211 return SDValue(); 10212 10213 // Optimize shl/srl/sra with constant shift amount. 10214 if (isSplatVector(Amt.getNode())) { 10215 SDValue SclrAmt = Amt->getOperand(0); 10216 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) { 10217 uint64_t ShiftAmt = C->getZExtValue(); 10218 10219 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) { 10220 // Make a large shift. 10221 SDValue SHL = 10222 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10223 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 10224 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10225 // Zero out the rightmost bits. 10226 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt), 10227 MVT::i8)); 10228 return DAG.getNode(ISD::AND, dl, VT, SHL, 10229 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 10230 } 10231 10232 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL) 10233 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10234 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 10235 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10236 10237 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL) 10238 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10239 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 10240 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10241 10242 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL) 10243 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10244 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 10245 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10246 10247 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) { 10248 // Make a large shift. 10249 SDValue SRL = 10250 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10251 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 10252 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10253 // Zero out the leftmost bits. 10254 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 10255 MVT::i8)); 10256 return DAG.getNode(ISD::AND, dl, VT, SRL, 10257 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 10258 } 10259 10260 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL) 10261 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10262 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 10263 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10264 10265 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL) 10266 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10267 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32), 10268 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10269 10270 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL) 10271 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10272 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 10273 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10274 10275 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA) 10276 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10277 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32), 10278 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10279 10280 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA) 10281 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10282 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32), 10283 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10284 10285 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) { 10286 if (ShiftAmt == 7) { 10287 // R s>> 7 === R s< 0 10288 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl); 10289 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R); 10290 } 10291 10292 // R s>> a === ((R u>> a) ^ m) - m 10293 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 10294 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt, 10295 MVT::i8)); 10296 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16); 10297 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 10298 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 10299 return Res; 10300 } 10301 10302 if (Subtarget->hasAVX2()) { 10303 if (VT == MVT::v4i64 && Op.getOpcode() == ISD::SHL) 10304 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10305 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32), 10306 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10307 10308 if (VT == MVT::v8i32 && Op.getOpcode() == ISD::SHL) 10309 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10310 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32), 10311 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10312 10313 if (VT == MVT::v16i16 && Op.getOpcode() == ISD::SHL) 10314 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10315 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32), 10316 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10317 10318 if (VT == MVT::v4i64 && Op.getOpcode() == ISD::SRL) 10319 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10320 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32), 10321 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10322 10323 if (VT == MVT::v8i32 && Op.getOpcode() == ISD::SRL) 10324 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10325 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32), 10326 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10327 10328 if (VT == MVT::v16i16 && Op.getOpcode() == ISD::SRL) 10329 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10330 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32), 10331 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10332 10333 if (VT == MVT::v8i32 && Op.getOpcode() == ISD::SRA) 10334 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10335 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32), 10336 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10337 10338 if (VT == MVT::v16i16 && Op.getOpcode() == ISD::SRA) 10339 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10340 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32), 10341 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10342 } 10343 } 10344 } 10345 10346 // Lower SHL with variable shift amount. 10347 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) { 10348 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10349 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 10350 Op.getOperand(1), DAG.getConstant(23, MVT::i32)); 10351 10352 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U)); 10353 10354 std::vector<Constant*> CV(4, CI); 10355 Constant *C = ConstantVector::get(CV); 10356 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 10357 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 10358 MachinePointerInfo::getConstantPool(), 10359 false, false, false, 16); 10360 10361 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend); 10362 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op); 10363 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op); 10364 return DAG.getNode(ISD::MUL, dl, VT, Op, R); 10365 } 10366 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) { 10367 // a = a << 5; 10368 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10369 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 10370 Op.getOperand(1), DAG.getConstant(5, MVT::i32)); 10371 10372 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15)); 10373 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63)); 10374 10375 std::vector<Constant*> CVM1(16, CM1); 10376 std::vector<Constant*> CVM2(16, CM2); 10377 Constant *C = ConstantVector::get(CVM1); 10378 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 10379 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 10380 MachinePointerInfo::getConstantPool(), 10381 false, false, false, 16); 10382 10383 // r = pblendv(r, psllw(r & (char16)15, 4), a); 10384 M = DAG.getNode(ISD::AND, dl, VT, R, M); 10385 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10386 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 10387 DAG.getConstant(4, MVT::i32)); 10388 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M); 10389 // a += a 10390 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 10391 10392 C = ConstantVector::get(CVM2); 10393 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 10394 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 10395 MachinePointerInfo::getConstantPool(), 10396 false, false, false, 16); 10397 10398 // r = pblendv(r, psllw(r & (char16)63, 2), a); 10399 M = DAG.getNode(ISD::AND, dl, VT, R, M); 10400 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10401 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 10402 DAG.getConstant(2, MVT::i32)); 10403 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M); 10404 // a += a 10405 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 10406 10407 // return pblendv(r, r+r, a); 10408 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, 10409 R, DAG.getNode(ISD::ADD, dl, VT, R, R)); 10410 return R; 10411 } 10412 10413 // Decompose 256-bit shifts into smaller 128-bit shifts. 10414 if (VT.getSizeInBits() == 256) { 10415 int NumElems = VT.getVectorNumElements(); 10416 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10417 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 10418 10419 // Extract the two vectors 10420 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl); 10421 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32), 10422 DAG, dl); 10423 10424 // Recreate the shift amount vectors 10425 SDValue Amt1, Amt2; 10426 if (Amt.getOpcode() == ISD::BUILD_VECTOR) { 10427 // Constant shift amount 10428 SmallVector<SDValue, 4> Amt1Csts; 10429 SmallVector<SDValue, 4> Amt2Csts; 10430 for (int i = 0; i < NumElems/2; ++i) 10431 Amt1Csts.push_back(Amt->getOperand(i)); 10432 for (int i = NumElems/2; i < NumElems; ++i) 10433 Amt2Csts.push_back(Amt->getOperand(i)); 10434 10435 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 10436 &Amt1Csts[0], NumElems/2); 10437 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 10438 &Amt2Csts[0], NumElems/2); 10439 } else { 10440 // Variable shift amount 10441 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl); 10442 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32), 10443 DAG, dl); 10444 } 10445 10446 // Issue new vector shifts for the smaller types 10447 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1); 10448 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2); 10449 10450 // Concatenate the result back 10451 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2); 10452 } 10453 10454 return SDValue(); 10455 } 10456 10457 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 10458 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus 10459 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering 10460 // looks for this combo and may remove the "setcc" instruction if the "setcc" 10461 // has only one use. 10462 SDNode *N = Op.getNode(); 10463 SDValue LHS = N->getOperand(0); 10464 SDValue RHS = N->getOperand(1); 10465 unsigned BaseOp = 0; 10466 unsigned Cond = 0; 10467 DebugLoc DL = Op.getDebugLoc(); 10468 switch (Op.getOpcode()) { 10469 default: llvm_unreachable("Unknown ovf instruction!"); 10470 case ISD::SADDO: 10471 // A subtract of one will be selected as a INC. Note that INC doesn't 10472 // set CF, so we can't do this for UADDO. 10473 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 10474 if (C->isOne()) { 10475 BaseOp = X86ISD::INC; 10476 Cond = X86::COND_O; 10477 break; 10478 } 10479 BaseOp = X86ISD::ADD; 10480 Cond = X86::COND_O; 10481 break; 10482 case ISD::UADDO: 10483 BaseOp = X86ISD::ADD; 10484 Cond = X86::COND_B; 10485 break; 10486 case ISD::SSUBO: 10487 // A subtract of one will be selected as a DEC. Note that DEC doesn't 10488 // set CF, so we can't do this for USUBO. 10489 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 10490 if (C->isOne()) { 10491 BaseOp = X86ISD::DEC; 10492 Cond = X86::COND_O; 10493 break; 10494 } 10495 BaseOp = X86ISD::SUB; 10496 Cond = X86::COND_O; 10497 break; 10498 case ISD::USUBO: 10499 BaseOp = X86ISD::SUB; 10500 Cond = X86::COND_B; 10501 break; 10502 case ISD::SMULO: 10503 BaseOp = X86ISD::SMUL; 10504 Cond = X86::COND_O; 10505 break; 10506 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs 10507 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0), 10508 MVT::i32); 10509 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS); 10510 10511 SDValue SetCC = 10512 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 10513 DAG.getConstant(X86::COND_O, MVT::i32), 10514 SDValue(Sum.getNode(), 2)); 10515 10516 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 10517 } 10518 } 10519 10520 // Also sets EFLAGS. 10521 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 10522 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 10523 10524 SDValue SetCC = 10525 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1), 10526 DAG.getConstant(Cond, MVT::i32), 10527 SDValue(Sum.getNode(), 1)); 10528 10529 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 10530 } 10531 10532 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{ 10533 DebugLoc dl = Op.getDebugLoc(); 10534 SDNode* Node = Op.getNode(); 10535 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 10536 EVT VT = Node->getValueType(0); 10537 if (Subtarget->hasXMMInt() && VT.isVector()) { 10538 unsigned BitsDiff = VT.getScalarType().getSizeInBits() - 10539 ExtraVT.getScalarType().getSizeInBits(); 10540 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32); 10541 10542 unsigned SHLIntrinsicsID = 0; 10543 unsigned SRAIntrinsicsID = 0; 10544 switch (VT.getSimpleVT().SimpleTy) { 10545 default: 10546 return SDValue(); 10547 case MVT::v4i32: { 10548 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d; 10549 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d; 10550 break; 10551 } 10552 case MVT::v8i16: { 10553 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w; 10554 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w; 10555 break; 10556 } 10557 } 10558 10559 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10560 DAG.getConstant(SHLIntrinsicsID, MVT::i32), 10561 Node->getOperand(0), ShAmt); 10562 10563 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10564 DAG.getConstant(SRAIntrinsicsID, MVT::i32), 10565 Tmp1, ShAmt); 10566 } 10567 10568 return SDValue(); 10569 } 10570 10571 10572 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{ 10573 DebugLoc dl = Op.getDebugLoc(); 10574 10575 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2. 10576 // There isn't any reason to disable it if the target processor supports it. 10577 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) { 10578 SDValue Chain = Op.getOperand(0); 10579 SDValue Zero = DAG.getConstant(0, MVT::i32); 10580 SDValue Ops[] = { 10581 DAG.getRegister(X86::ESP, MVT::i32), // Base 10582 DAG.getTargetConstant(1, MVT::i8), // Scale 10583 DAG.getRegister(0, MVT::i32), // Index 10584 DAG.getTargetConstant(0, MVT::i32), // Disp 10585 DAG.getRegister(0, MVT::i32), // Segment. 10586 Zero, 10587 Chain 10588 }; 10589 SDNode *Res = 10590 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 10591 array_lengthof(Ops)); 10592 return SDValue(Res, 0); 10593 } 10594 10595 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 10596 if (!isDev) 10597 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 10598 10599 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 10600 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 10601 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 10602 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 10603 10604 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>; 10605 if (!Op1 && !Op2 && !Op3 && Op4) 10606 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0)); 10607 10608 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>; 10609 if (Op1 && !Op2 && !Op3 && !Op4) 10610 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0)); 10611 10612 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 10613 // (MFENCE)>; 10614 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 10615 } 10616 10617 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op, 10618 SelectionDAG &DAG) const { 10619 DebugLoc dl = Op.getDebugLoc(); 10620 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>( 10621 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()); 10622 SynchronizationScope FenceScope = static_cast<SynchronizationScope>( 10623 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 10624 10625 // The only fence that needs an instruction is a sequentially-consistent 10626 // cross-thread fence. 10627 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) { 10628 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for 10629 // no-sse2). There isn't any reason to disable it if the target processor 10630 // supports it. 10631 if (Subtarget->hasXMMInt() || Subtarget->is64Bit()) 10632 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 10633 10634 SDValue Chain = Op.getOperand(0); 10635 SDValue Zero = DAG.getConstant(0, MVT::i32); 10636 SDValue Ops[] = { 10637 DAG.getRegister(X86::ESP, MVT::i32), // Base 10638 DAG.getTargetConstant(1, MVT::i8), // Scale 10639 DAG.getRegister(0, MVT::i32), // Index 10640 DAG.getTargetConstant(0, MVT::i32), // Disp 10641 DAG.getRegister(0, MVT::i32), // Segment. 10642 Zero, 10643 Chain 10644 }; 10645 SDNode *Res = 10646 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 10647 array_lengthof(Ops)); 10648 return SDValue(Res, 0); 10649 } 10650 10651 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 10652 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 10653 } 10654 10655 10656 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 10657 EVT T = Op.getValueType(); 10658 DebugLoc DL = Op.getDebugLoc(); 10659 unsigned Reg = 0; 10660 unsigned size = 0; 10661 switch(T.getSimpleVT().SimpleTy) { 10662 default: 10663 assert(false && "Invalid value type!"); 10664 case MVT::i8: Reg = X86::AL; size = 1; break; 10665 case MVT::i16: Reg = X86::AX; size = 2; break; 10666 case MVT::i32: Reg = X86::EAX; size = 4; break; 10667 case MVT::i64: 10668 assert(Subtarget->is64Bit() && "Node not type legal!"); 10669 Reg = X86::RAX; size = 8; 10670 break; 10671 } 10672 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg, 10673 Op.getOperand(2), SDValue()); 10674 SDValue Ops[] = { cpIn.getValue(0), 10675 Op.getOperand(1), 10676 Op.getOperand(3), 10677 DAG.getTargetConstant(size, MVT::i8), 10678 cpIn.getValue(1) }; 10679 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10680 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand(); 10681 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys, 10682 Ops, 5, T, MMO); 10683 SDValue cpOut = 10684 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1)); 10685 return cpOut; 10686 } 10687 10688 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op, 10689 SelectionDAG &DAG) const { 10690 assert(Subtarget->is64Bit() && "Result not type legalized?"); 10691 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10692 SDValue TheChain = Op.getOperand(0); 10693 DebugLoc dl = Op.getDebugLoc(); 10694 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 10695 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1)); 10696 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64, 10697 rax.getValue(2)); 10698 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx, 10699 DAG.getConstant(32, MVT::i8)); 10700 SDValue Ops[] = { 10701 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp), 10702 rdx.getValue(1) 10703 }; 10704 return DAG.getMergeValues(Ops, 2, dl); 10705 } 10706 10707 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, 10708 SelectionDAG &DAG) const { 10709 EVT SrcVT = Op.getOperand(0).getValueType(); 10710 EVT DstVT = Op.getValueType(); 10711 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() && 10712 Subtarget->hasMMX() && "Unexpected custom BITCAST"); 10713 assert((DstVT == MVT::i64 || 10714 (DstVT.isVector() && DstVT.getSizeInBits()==64)) && 10715 "Unexpected custom BITCAST"); 10716 // i64 <=> MMX conversions are Legal. 10717 if (SrcVT==MVT::i64 && DstVT.isVector()) 10718 return Op; 10719 if (DstVT==MVT::i64 && SrcVT.isVector()) 10720 return Op; 10721 // MMX <=> MMX conversions are Legal. 10722 if (SrcVT.isVector() && DstVT.isVector()) 10723 return Op; 10724 // All other conversions need to be expanded. 10725 return SDValue(); 10726 } 10727 10728 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const { 10729 SDNode *Node = Op.getNode(); 10730 DebugLoc dl = Node->getDebugLoc(); 10731 EVT T = Node->getValueType(0); 10732 SDValue negOp = DAG.getNode(ISD::SUB, dl, T, 10733 DAG.getConstant(0, T), Node->getOperand(2)); 10734 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, 10735 cast<AtomicSDNode>(Node)->getMemoryVT(), 10736 Node->getOperand(0), 10737 Node->getOperand(1), negOp, 10738 cast<AtomicSDNode>(Node)->getSrcValue(), 10739 cast<AtomicSDNode>(Node)->getAlignment(), 10740 cast<AtomicSDNode>(Node)->getOrdering(), 10741 cast<AtomicSDNode>(Node)->getSynchScope()); 10742 } 10743 10744 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) { 10745 SDNode *Node = Op.getNode(); 10746 DebugLoc dl = Node->getDebugLoc(); 10747 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 10748 10749 // Convert seq_cst store -> xchg 10750 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b) 10751 // FIXME: On 32-bit, store -> fist or movq would be more efficient 10752 // (The only way to get a 16-byte store is cmpxchg16b) 10753 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment. 10754 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent || 10755 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10756 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 10757 cast<AtomicSDNode>(Node)->getMemoryVT(), 10758 Node->getOperand(0), 10759 Node->getOperand(1), Node->getOperand(2), 10760 cast<AtomicSDNode>(Node)->getMemOperand(), 10761 cast<AtomicSDNode>(Node)->getOrdering(), 10762 cast<AtomicSDNode>(Node)->getSynchScope()); 10763 return Swap.getValue(1); 10764 } 10765 // Other atomic stores have a simple pattern. 10766 return Op; 10767 } 10768 10769 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 10770 EVT VT = Op.getNode()->getValueType(0); 10771 10772 // Let legalize expand this if it isn't a legal type yet. 10773 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10774 return SDValue(); 10775 10776 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 10777 10778 unsigned Opc; 10779 bool ExtraOp = false; 10780 switch (Op.getOpcode()) { 10781 default: assert(0 && "Invalid code"); 10782 case ISD::ADDC: Opc = X86ISD::ADD; break; 10783 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break; 10784 case ISD::SUBC: Opc = X86ISD::SUB; break; 10785 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break; 10786 } 10787 10788 if (!ExtraOp) 10789 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 10790 Op.getOperand(1)); 10791 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 10792 Op.getOperand(1), Op.getOperand(2)); 10793 } 10794 10795 /// LowerOperation - Provide custom lowering hooks for some operations. 10796 /// 10797 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10798 switch (Op.getOpcode()) { 10799 default: llvm_unreachable("Should not custom lower this!"); 10800 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG); 10801 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG); 10802 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG); 10803 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG); 10804 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG); 10805 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG); 10806 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10807 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 10808 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10809 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10810 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10811 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG); 10812 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG); 10813 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10814 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10815 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10816 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10817 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); 10818 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10819 case ISD::SHL_PARTS: 10820 case ISD::SRA_PARTS: 10821 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG); 10822 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 10823 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG); 10824 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 10825 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG); 10826 case ISD::FABS: return LowerFABS(Op, DAG); 10827 case ISD::FNEG: return LowerFNEG(Op, DAG); 10828 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 10829 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG); 10830 case ISD::SETCC: return LowerSETCC(Op, DAG); 10831 case ISD::SELECT: return LowerSELECT(Op, DAG); 10832 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 10833 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10834 case ISD::VASTART: return LowerVASTART(Op, DAG); 10835 case ISD::VAARG: return LowerVAARG(Op, DAG); 10836 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10837 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10838 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10839 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10840 case ISD::FRAME_TO_ARGS_OFFSET: 10841 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG); 10842 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10843 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG); 10844 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10845 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10846 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10847 case ISD::CTLZ: return LowerCTLZ(Op, DAG); 10848 case ISD::CTTZ: return LowerCTTZ(Op, DAG); 10849 case ISD::MUL: return LowerMUL(Op, DAG); 10850 case ISD::SRA: 10851 case ISD::SRL: 10852 case ISD::SHL: return LowerShift(Op, DAG); 10853 case ISD::SADDO: 10854 case ISD::UADDO: 10855 case ISD::SSUBO: 10856 case ISD::USUBO: 10857 case ISD::SMULO: 10858 case ISD::UMULO: return LowerXALUO(Op, DAG); 10859 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG); 10860 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10861 case ISD::ADDC: 10862 case ISD::ADDE: 10863 case ISD::SUBC: 10864 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 10865 case ISD::ADD: return LowerADD(Op, DAG); 10866 case ISD::SUB: return LowerSUB(Op, DAG); 10867 } 10868 } 10869 10870 static void ReplaceATOMIC_LOAD(SDNode *Node, 10871 SmallVectorImpl<SDValue> &Results, 10872 SelectionDAG &DAG) { 10873 DebugLoc dl = Node->getDebugLoc(); 10874 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 10875 10876 // Convert wide load -> cmpxchg8b/cmpxchg16b 10877 // FIXME: On 32-bit, load -> fild or movq would be more efficient 10878 // (The only way to get a 16-byte load is cmpxchg16b) 10879 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment. 10880 SDValue Zero = DAG.getConstant(0, VT); 10881 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT, 10882 Node->getOperand(0), 10883 Node->getOperand(1), Zero, Zero, 10884 cast<AtomicSDNode>(Node)->getMemOperand(), 10885 cast<AtomicSDNode>(Node)->getOrdering(), 10886 cast<AtomicSDNode>(Node)->getSynchScope()); 10887 Results.push_back(Swap.getValue(0)); 10888 Results.push_back(Swap.getValue(1)); 10889 } 10890 10891 void X86TargetLowering:: 10892 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results, 10893 SelectionDAG &DAG, unsigned NewOp) const { 10894 DebugLoc dl = Node->getDebugLoc(); 10895 assert (Node->getValueType(0) == MVT::i64 && 10896 "Only know how to expand i64 atomics"); 10897 10898 SDValue Chain = Node->getOperand(0); 10899 SDValue In1 = Node->getOperand(1); 10900 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 10901 Node->getOperand(2), DAG.getIntPtrConstant(0)); 10902 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 10903 Node->getOperand(2), DAG.getIntPtrConstant(1)); 10904 SDValue Ops[] = { Chain, In1, In2L, In2H }; 10905 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10906 SDValue Result = 10907 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64, 10908 cast<MemSDNode>(Node)->getMemOperand()); 10909 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)}; 10910 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 10911 Results.push_back(Result.getValue(2)); 10912 } 10913 10914 /// ReplaceNodeResults - Replace a node with an illegal result type 10915 /// with a new node built out of custom code. 10916 void X86TargetLowering::ReplaceNodeResults(SDNode *N, 10917 SmallVectorImpl<SDValue>&Results, 10918 SelectionDAG &DAG) const { 10919 DebugLoc dl = N->getDebugLoc(); 10920 switch (N->getOpcode()) { 10921 default: 10922 assert(false && "Do not know how to custom type legalize this operation!"); 10923 return; 10924 case ISD::SIGN_EXTEND_INREG: 10925 case ISD::ADDC: 10926 case ISD::ADDE: 10927 case ISD::SUBC: 10928 case ISD::SUBE: 10929 // We don't want to expand or promote these. 10930 return; 10931 case ISD::FP_TO_SINT: { 10932 std::pair<SDValue,SDValue> Vals = 10933 FP_TO_INTHelper(SDValue(N, 0), DAG, true); 10934 SDValue FIST = Vals.first, StackSlot = Vals.second; 10935 if (FIST.getNode() != 0) { 10936 EVT VT = N->getValueType(0); 10937 // Return a load from the stack slot. 10938 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, 10939 MachinePointerInfo(), 10940 false, false, false, 0)); 10941 } 10942 return; 10943 } 10944 case ISD::READCYCLECOUNTER: { 10945 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10946 SDValue TheChain = N->getOperand(0); 10947 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 10948 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32, 10949 rd.getValue(1)); 10950 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32, 10951 eax.getValue(2)); 10952 // Use a buildpair to merge the two 32-bit values into a 64-bit one. 10953 SDValue Ops[] = { eax, edx }; 10954 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2)); 10955 Results.push_back(edx.getValue(1)); 10956 return; 10957 } 10958 case ISD::ATOMIC_CMP_SWAP: { 10959 EVT T = N->getValueType(0); 10960 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair"); 10961 bool Regs64bit = T == MVT::i128; 10962 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32; 10963 SDValue cpInL, cpInH; 10964 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 10965 DAG.getConstant(0, HalfT)); 10966 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 10967 DAG.getConstant(1, HalfT)); 10968 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, 10969 Regs64bit ? X86::RAX : X86::EAX, 10970 cpInL, SDValue()); 10971 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, 10972 Regs64bit ? X86::RDX : X86::EDX, 10973 cpInH, cpInL.getValue(1)); 10974 SDValue swapInL, swapInH; 10975 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 10976 DAG.getConstant(0, HalfT)); 10977 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 10978 DAG.getConstant(1, HalfT)); 10979 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, 10980 Regs64bit ? X86::RBX : X86::EBX, 10981 swapInL, cpInH.getValue(1)); 10982 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, 10983 Regs64bit ? X86::RCX : X86::ECX, 10984 swapInH, swapInL.getValue(1)); 10985 SDValue Ops[] = { swapInH.getValue(0), 10986 N->getOperand(1), 10987 swapInH.getValue(1) }; 10988 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10989 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 10990 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG : 10991 X86ISD::LCMPXCHG8_DAG; 10992 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, 10993 Ops, 3, T, MMO); 10994 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, 10995 Regs64bit ? X86::RAX : X86::EAX, 10996 HalfT, Result.getValue(1)); 10997 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, 10998 Regs64bit ? X86::RDX : X86::EDX, 10999 HalfT, cpOutL.getValue(2)); 11000 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)}; 11001 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2)); 11002 Results.push_back(cpOutH.getValue(1)); 11003 return; 11004 } 11005 case ISD::ATOMIC_LOAD_ADD: 11006 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG); 11007 return; 11008 case ISD::ATOMIC_LOAD_AND: 11009 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG); 11010 return; 11011 case ISD::ATOMIC_LOAD_NAND: 11012 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG); 11013 return; 11014 case ISD::ATOMIC_LOAD_OR: 11015 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG); 11016 return; 11017 case ISD::ATOMIC_LOAD_SUB: 11018 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG); 11019 return; 11020 case ISD::ATOMIC_LOAD_XOR: 11021 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG); 11022 return; 11023 case ISD::ATOMIC_SWAP: 11024 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG); 11025 return; 11026 case ISD::ATOMIC_LOAD: 11027 ReplaceATOMIC_LOAD(N, Results, DAG); 11028 } 11029 } 11030 11031 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const { 11032 switch (Opcode) { 11033 default: return NULL; 11034 case X86ISD::BSF: return "X86ISD::BSF"; 11035 case X86ISD::BSR: return "X86ISD::BSR"; 11036 case X86ISD::SHLD: return "X86ISD::SHLD"; 11037 case X86ISD::SHRD: return "X86ISD::SHRD"; 11038 case X86ISD::FAND: return "X86ISD::FAND"; 11039 case X86ISD::FOR: return "X86ISD::FOR"; 11040 case X86ISD::FXOR: return "X86ISD::FXOR"; 11041 case X86ISD::FSRL: return "X86ISD::FSRL"; 11042 case X86ISD::FILD: return "X86ISD::FILD"; 11043 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG"; 11044 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM"; 11045 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM"; 11046 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM"; 11047 case X86ISD::FLD: return "X86ISD::FLD"; 11048 case X86ISD::FST: return "X86ISD::FST"; 11049 case X86ISD::CALL: return "X86ISD::CALL"; 11050 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG"; 11051 case X86ISD::BT: return "X86ISD::BT"; 11052 case X86ISD::CMP: return "X86ISD::CMP"; 11053 case X86ISD::COMI: return "X86ISD::COMI"; 11054 case X86ISD::UCOMI: return "X86ISD::UCOMI"; 11055 case X86ISD::SETCC: return "X86ISD::SETCC"; 11056 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY"; 11057 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd"; 11058 case X86ISD::FSETCCss: return "X86ISD::FSETCCss"; 11059 case X86ISD::CMOV: return "X86ISD::CMOV"; 11060 case X86ISD::BRCOND: return "X86ISD::BRCOND"; 11061 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG"; 11062 case X86ISD::REP_STOS: return "X86ISD::REP_STOS"; 11063 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS"; 11064 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg"; 11065 case X86ISD::Wrapper: return "X86ISD::Wrapper"; 11066 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP"; 11067 case X86ISD::PEXTRB: return "X86ISD::PEXTRB"; 11068 case X86ISD::PEXTRW: return "X86ISD::PEXTRW"; 11069 case X86ISD::INSERTPS: return "X86ISD::INSERTPS"; 11070 case X86ISD::PINSRB: return "X86ISD::PINSRB"; 11071 case X86ISD::PINSRW: return "X86ISD::PINSRW"; 11072 case X86ISD::PSHUFB: return "X86ISD::PSHUFB"; 11073 case X86ISD::ANDNP: return "X86ISD::ANDNP"; 11074 case X86ISD::PSIGNB: return "X86ISD::PSIGNB"; 11075 case X86ISD::PSIGNW: return "X86ISD::PSIGNW"; 11076 case X86ISD::PSIGND: return "X86ISD::PSIGND"; 11077 case X86ISD::BLENDV: return "X86ISD::BLENDV"; 11078 case X86ISD::FHADD: return "X86ISD::FHADD"; 11079 case X86ISD::FHSUB: return "X86ISD::FHSUB"; 11080 case X86ISD::FMAX: return "X86ISD::FMAX"; 11081 case X86ISD::FMIN: return "X86ISD::FMIN"; 11082 case X86ISD::FRSQRT: return "X86ISD::FRSQRT"; 11083 case X86ISD::FRCP: return "X86ISD::FRCP"; 11084 case X86ISD::TLSADDR: return "X86ISD::TLSADDR"; 11085 case X86ISD::TLSCALL: return "X86ISD::TLSCALL"; 11086 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN"; 11087 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN"; 11088 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m"; 11089 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG"; 11090 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG"; 11091 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG"; 11092 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG"; 11093 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG"; 11094 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG"; 11095 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG"; 11096 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG"; 11097 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL"; 11098 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD"; 11099 case X86ISD::VSHL: return "X86ISD::VSHL"; 11100 case X86ISD::VSRL: return "X86ISD::VSRL"; 11101 case X86ISD::CMPPD: return "X86ISD::CMPPD"; 11102 case X86ISD::CMPPS: return "X86ISD::CMPPS"; 11103 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB"; 11104 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW"; 11105 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD"; 11106 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ"; 11107 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB"; 11108 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW"; 11109 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD"; 11110 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ"; 11111 case X86ISD::ADD: return "X86ISD::ADD"; 11112 case X86ISD::SUB: return "X86ISD::SUB"; 11113 case X86ISD::ADC: return "X86ISD::ADC"; 11114 case X86ISD::SBB: return "X86ISD::SBB"; 11115 case X86ISD::SMUL: return "X86ISD::SMUL"; 11116 case X86ISD::UMUL: return "X86ISD::UMUL"; 11117 case X86ISD::INC: return "X86ISD::INC"; 11118 case X86ISD::DEC: return "X86ISD::DEC"; 11119 case X86ISD::OR: return "X86ISD::OR"; 11120 case X86ISD::XOR: return "X86ISD::XOR"; 11121 case X86ISD::AND: return "X86ISD::AND"; 11122 case X86ISD::ANDN: return "X86ISD::ANDN"; 11123 case X86ISD::BLSI: return "X86ISD::BLSI"; 11124 case X86ISD::BLSMSK: return "X86ISD::BLSMSK"; 11125 case X86ISD::BLSR: return "X86ISD::BLSR"; 11126 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM"; 11127 case X86ISD::PTEST: return "X86ISD::PTEST"; 11128 case X86ISD::TESTP: return "X86ISD::TESTP"; 11129 case X86ISD::PALIGN: return "X86ISD::PALIGN"; 11130 case X86ISD::PSHUFD: return "X86ISD::PSHUFD"; 11131 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW"; 11132 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD"; 11133 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW"; 11134 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD"; 11135 case X86ISD::SHUFPS: return "X86ISD::SHUFPS"; 11136 case X86ISD::SHUFPD: return "X86ISD::SHUFPD"; 11137 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS"; 11138 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD"; 11139 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS"; 11140 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD"; 11141 case X86ISD::MOVLPS: return "X86ISD::MOVLPS"; 11142 case X86ISD::MOVLPD: return "X86ISD::MOVLPD"; 11143 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP"; 11144 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP"; 11145 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP"; 11146 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD"; 11147 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD"; 11148 case X86ISD::MOVSD: return "X86ISD::MOVSD"; 11149 case X86ISD::MOVSS: return "X86ISD::MOVSS"; 11150 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS"; 11151 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD"; 11152 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY"; 11153 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS"; 11154 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD"; 11155 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW"; 11156 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD"; 11157 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ"; 11158 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ"; 11159 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW"; 11160 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD"; 11161 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ"; 11162 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ"; 11163 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST"; 11164 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS"; 11165 case X86ISD::VPERMILPSY: return "X86ISD::VPERMILPSY"; 11166 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD"; 11167 case X86ISD::VPERMILPDY: return "X86ISD::VPERMILPDY"; 11168 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128"; 11169 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS"; 11170 case X86ISD::VAARG_64: return "X86ISD::VAARG_64"; 11171 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA"; 11172 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER"; 11173 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA"; 11174 } 11175 } 11176 11177 // isLegalAddressingMode - Return true if the addressing mode represented 11178 // by AM is legal for this target, for a load/store of the specified type. 11179 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 11180 Type *Ty) const { 11181 // X86 supports extremely general addressing modes. 11182 CodeModel::Model M = getTargetMachine().getCodeModel(); 11183 Reloc::Model R = getTargetMachine().getRelocationModel(); 11184 11185 // X86 allows a sign-extended 32-bit immediate field as a displacement. 11186 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL)) 11187 return false; 11188 11189 if (AM.BaseGV) { 11190 unsigned GVFlags = 11191 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine()); 11192 11193 // If a reference to this global requires an extra load, we can't fold it. 11194 if (isGlobalStubReference(GVFlags)) 11195 return false; 11196 11197 // If BaseGV requires a register for the PIC base, we cannot also have a 11198 // BaseReg specified. 11199 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags)) 11200 return false; 11201 11202 // If lower 4G is not available, then we must use rip-relative addressing. 11203 if ((M != CodeModel::Small || R != Reloc::Static) && 11204 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1)) 11205 return false; 11206 } 11207 11208 switch (AM.Scale) { 11209 case 0: 11210 case 1: 11211 case 2: 11212 case 4: 11213 case 8: 11214 // These scales always work. 11215 break; 11216 case 3: 11217 case 5: 11218 case 9: 11219 // These scales are formed with basereg+scalereg. Only accept if there is 11220 // no basereg yet. 11221 if (AM.HasBaseReg) 11222 return false; 11223 break; 11224 default: // Other stuff never works. 11225 return false; 11226 } 11227 11228 return true; 11229 } 11230 11231 11232 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 11233 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11234 return false; 11235 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 11236 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 11237 if (NumBits1 <= NumBits2) 11238 return false; 11239 return true; 11240 } 11241 11242 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 11243 if (!VT1.isInteger() || !VT2.isInteger()) 11244 return false; 11245 unsigned NumBits1 = VT1.getSizeInBits(); 11246 unsigned NumBits2 = VT2.getSizeInBits(); 11247 if (NumBits1 <= NumBits2) 11248 return false; 11249 return true; 11250 } 11251 11252 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 11253 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 11254 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit(); 11255 } 11256 11257 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 11258 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 11259 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit(); 11260 } 11261 11262 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const { 11263 // i16 instructions are longer (0x66 prefix) and potentially slower. 11264 return !(VT1 == MVT::i32 && VT2 == MVT::i16); 11265 } 11266 11267 /// isShuffleMaskLegal - Targets can use this to indicate that they only 11268 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 11269 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 11270 /// are assumed to be legal. 11271 bool 11272 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 11273 EVT VT) const { 11274 // Very little shuffling can be done for 64-bit vectors right now. 11275 if (VT.getSizeInBits() == 64) 11276 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()); 11277 11278 // FIXME: pshufb, blends, shifts. 11279 return (VT.getVectorNumElements() == 2 || 11280 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 11281 isMOVLMask(M, VT) || 11282 isSHUFPMask(M, VT) || 11283 isPSHUFDMask(M, VT) || 11284 isPSHUFHWMask(M, VT) || 11285 isPSHUFLWMask(M, VT) || 11286 isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) || 11287 isUNPCKLMask(M, VT) || 11288 isUNPCKHMask(M, VT) || 11289 isUNPCKL_v_undef_Mask(M, VT) || 11290 isUNPCKH_v_undef_Mask(M, VT)); 11291 } 11292 11293 bool 11294 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 11295 EVT VT) const { 11296 unsigned NumElts = VT.getVectorNumElements(); 11297 // FIXME: This collection of masks seems suspect. 11298 if (NumElts == 2) 11299 return true; 11300 if (NumElts == 4 && VT.getSizeInBits() == 128) { 11301 return (isMOVLMask(Mask, VT) || 11302 isCommutedMOVLMask(Mask, VT, true) || 11303 isSHUFPMask(Mask, VT) || 11304 isCommutedSHUFPMask(Mask, VT)); 11305 } 11306 return false; 11307 } 11308 11309 //===----------------------------------------------------------------------===// 11310 // X86 Scheduler Hooks 11311 //===----------------------------------------------------------------------===// 11312 11313 // private utility function 11314 MachineBasicBlock * 11315 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr, 11316 MachineBasicBlock *MBB, 11317 unsigned regOpc, 11318 unsigned immOpc, 11319 unsigned LoadOpc, 11320 unsigned CXchgOpc, 11321 unsigned notOpc, 11322 unsigned EAXreg, 11323 TargetRegisterClass *RC, 11324 bool invSrc) const { 11325 // For the atomic bitwise operator, we generate 11326 // thisMBB: 11327 // newMBB: 11328 // ld t1 = [bitinstr.addr] 11329 // op t2 = t1, [bitinstr.val] 11330 // mov EAX = t1 11331 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 11332 // bz newMBB 11333 // fallthrough -->nextMBB 11334 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11335 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11336 MachineFunction::iterator MBBIter = MBB; 11337 ++MBBIter; 11338 11339 /// First build the CFG 11340 MachineFunction *F = MBB->getParent(); 11341 MachineBasicBlock *thisMBB = MBB; 11342 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11343 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11344 F->insert(MBBIter, newMBB); 11345 F->insert(MBBIter, nextMBB); 11346 11347 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11348 nextMBB->splice(nextMBB->begin(), thisMBB, 11349 llvm::next(MachineBasicBlock::iterator(bInstr)), 11350 thisMBB->end()); 11351 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11352 11353 // Update thisMBB to fall through to newMBB 11354 thisMBB->addSuccessor(newMBB); 11355 11356 // newMBB jumps to itself and fall through to nextMBB 11357 newMBB->addSuccessor(nextMBB); 11358 newMBB->addSuccessor(newMBB); 11359 11360 // Insert instructions into newMBB based on incoming instruction 11361 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 && 11362 "unexpected number of operands"); 11363 DebugLoc dl = bInstr->getDebugLoc(); 11364 MachineOperand& destOper = bInstr->getOperand(0); 11365 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11366 int numArgs = bInstr->getNumOperands() - 1; 11367 for (int i=0; i < numArgs; ++i) 11368 argOpers[i] = &bInstr->getOperand(i+1); 11369 11370 // x86 address has 4 operands: base, index, scale, and displacement 11371 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11372 int valArgIndx = lastAddrIndx + 1; 11373 11374 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 11375 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1); 11376 for (int i=0; i <= lastAddrIndx; ++i) 11377 (*MIB).addOperand(*argOpers[i]); 11378 11379 unsigned tt = F->getRegInfo().createVirtualRegister(RC); 11380 if (invSrc) { 11381 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1); 11382 } 11383 else 11384 tt = t1; 11385 11386 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 11387 assert((argOpers[valArgIndx]->isReg() || 11388 argOpers[valArgIndx]->isImm()) && 11389 "invalid operand"); 11390 if (argOpers[valArgIndx]->isReg()) 11391 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2); 11392 else 11393 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2); 11394 MIB.addReg(tt); 11395 (*MIB).addOperand(*argOpers[valArgIndx]); 11396 11397 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg); 11398 MIB.addReg(t1); 11399 11400 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc)); 11401 for (int i=0; i <= lastAddrIndx; ++i) 11402 (*MIB).addOperand(*argOpers[i]); 11403 MIB.addReg(t2); 11404 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11405 (*MIB).setMemRefs(bInstr->memoperands_begin(), 11406 bInstr->memoperands_end()); 11407 11408 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 11409 MIB.addReg(EAXreg); 11410 11411 // insert branch 11412 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11413 11414 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 11415 return nextMBB; 11416 } 11417 11418 // private utility function: 64 bit atomics on 32 bit host. 11419 MachineBasicBlock * 11420 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr, 11421 MachineBasicBlock *MBB, 11422 unsigned regOpcL, 11423 unsigned regOpcH, 11424 unsigned immOpcL, 11425 unsigned immOpcH, 11426 bool invSrc) const { 11427 // For the atomic bitwise operator, we generate 11428 // thisMBB (instructions are in pairs, except cmpxchg8b) 11429 // ld t1,t2 = [bitinstr.addr] 11430 // newMBB: 11431 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4) 11432 // op t5, t6 <- out1, out2, [bitinstr.val] 11433 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val]) 11434 // mov ECX, EBX <- t5, t6 11435 // mov EAX, EDX <- t1, t2 11436 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit] 11437 // mov t3, t4 <- EAX, EDX 11438 // bz newMBB 11439 // result in out1, out2 11440 // fallthrough -->nextMBB 11441 11442 const TargetRegisterClass *RC = X86::GR32RegisterClass; 11443 const unsigned LoadOpc = X86::MOV32rm; 11444 const unsigned NotOpc = X86::NOT32r; 11445 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11446 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11447 MachineFunction::iterator MBBIter = MBB; 11448 ++MBBIter; 11449 11450 /// First build the CFG 11451 MachineFunction *F = MBB->getParent(); 11452 MachineBasicBlock *thisMBB = MBB; 11453 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11454 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11455 F->insert(MBBIter, newMBB); 11456 F->insert(MBBIter, nextMBB); 11457 11458 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11459 nextMBB->splice(nextMBB->begin(), thisMBB, 11460 llvm::next(MachineBasicBlock::iterator(bInstr)), 11461 thisMBB->end()); 11462 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11463 11464 // Update thisMBB to fall through to newMBB 11465 thisMBB->addSuccessor(newMBB); 11466 11467 // newMBB jumps to itself and fall through to nextMBB 11468 newMBB->addSuccessor(nextMBB); 11469 newMBB->addSuccessor(newMBB); 11470 11471 DebugLoc dl = bInstr->getDebugLoc(); 11472 // Insert instructions into newMBB based on incoming instruction 11473 // There are 8 "real" operands plus 9 implicit def/uses, ignored here. 11474 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 && 11475 "unexpected number of operands"); 11476 MachineOperand& dest1Oper = bInstr->getOperand(0); 11477 MachineOperand& dest2Oper = bInstr->getOperand(1); 11478 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11479 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) { 11480 argOpers[i] = &bInstr->getOperand(i+2); 11481 11482 // We use some of the operands multiple times, so conservatively just 11483 // clear any kill flags that might be present. 11484 if (argOpers[i]->isReg() && argOpers[i]->isUse()) 11485 argOpers[i]->setIsKill(false); 11486 } 11487 11488 // x86 address has 5 operands: base, index, scale, displacement, and segment. 11489 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11490 11491 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 11492 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1); 11493 for (int i=0; i <= lastAddrIndx; ++i) 11494 (*MIB).addOperand(*argOpers[i]); 11495 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 11496 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2); 11497 // add 4 to displacement. 11498 for (int i=0; i <= lastAddrIndx-2; ++i) 11499 (*MIB).addOperand(*argOpers[i]); 11500 MachineOperand newOp3 = *(argOpers[3]); 11501 if (newOp3.isImm()) 11502 newOp3.setImm(newOp3.getImm()+4); 11503 else 11504 newOp3.setOffset(newOp3.getOffset()+4); 11505 (*MIB).addOperand(newOp3); 11506 (*MIB).addOperand(*argOpers[lastAddrIndx]); 11507 11508 // t3/4 are defined later, at the bottom of the loop 11509 unsigned t3 = F->getRegInfo().createVirtualRegister(RC); 11510 unsigned t4 = F->getRegInfo().createVirtualRegister(RC); 11511 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg()) 11512 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB); 11513 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg()) 11514 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB); 11515 11516 // The subsequent operations should be using the destination registers of 11517 //the PHI instructions. 11518 if (invSrc) { 11519 t1 = F->getRegInfo().createVirtualRegister(RC); 11520 t2 = F->getRegInfo().createVirtualRegister(RC); 11521 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg()); 11522 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg()); 11523 } else { 11524 t1 = dest1Oper.getReg(); 11525 t2 = dest2Oper.getReg(); 11526 } 11527 11528 int valArgIndx = lastAddrIndx + 1; 11529 assert((argOpers[valArgIndx]->isReg() || 11530 argOpers[valArgIndx]->isImm()) && 11531 "invalid operand"); 11532 unsigned t5 = F->getRegInfo().createVirtualRegister(RC); 11533 unsigned t6 = F->getRegInfo().createVirtualRegister(RC); 11534 if (argOpers[valArgIndx]->isReg()) 11535 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5); 11536 else 11537 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5); 11538 if (regOpcL != X86::MOV32rr) 11539 MIB.addReg(t1); 11540 (*MIB).addOperand(*argOpers[valArgIndx]); 11541 assert(argOpers[valArgIndx + 1]->isReg() == 11542 argOpers[valArgIndx]->isReg()); 11543 assert(argOpers[valArgIndx + 1]->isImm() == 11544 argOpers[valArgIndx]->isImm()); 11545 if (argOpers[valArgIndx + 1]->isReg()) 11546 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6); 11547 else 11548 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6); 11549 if (regOpcH != X86::MOV32rr) 11550 MIB.addReg(t2); 11551 (*MIB).addOperand(*argOpers[valArgIndx + 1]); 11552 11553 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 11554 MIB.addReg(t1); 11555 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX); 11556 MIB.addReg(t2); 11557 11558 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX); 11559 MIB.addReg(t5); 11560 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX); 11561 MIB.addReg(t6); 11562 11563 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B)); 11564 for (int i=0; i <= lastAddrIndx; ++i) 11565 (*MIB).addOperand(*argOpers[i]); 11566 11567 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11568 (*MIB).setMemRefs(bInstr->memoperands_begin(), 11569 bInstr->memoperands_end()); 11570 11571 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3); 11572 MIB.addReg(X86::EAX); 11573 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4); 11574 MIB.addReg(X86::EDX); 11575 11576 // insert branch 11577 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11578 11579 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 11580 return nextMBB; 11581 } 11582 11583 // private utility function 11584 MachineBasicBlock * 11585 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr, 11586 MachineBasicBlock *MBB, 11587 unsigned cmovOpc) const { 11588 // For the atomic min/max operator, we generate 11589 // thisMBB: 11590 // newMBB: 11591 // ld t1 = [min/max.addr] 11592 // mov t2 = [min/max.val] 11593 // cmp t1, t2 11594 // cmov[cond] t2 = t1 11595 // mov EAX = t1 11596 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 11597 // bz newMBB 11598 // fallthrough -->nextMBB 11599 // 11600 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11601 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11602 MachineFunction::iterator MBBIter = MBB; 11603 ++MBBIter; 11604 11605 /// First build the CFG 11606 MachineFunction *F = MBB->getParent(); 11607 MachineBasicBlock *thisMBB = MBB; 11608 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11609 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11610 F->insert(MBBIter, newMBB); 11611 F->insert(MBBIter, nextMBB); 11612 11613 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11614 nextMBB->splice(nextMBB->begin(), thisMBB, 11615 llvm::next(MachineBasicBlock::iterator(mInstr)), 11616 thisMBB->end()); 11617 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11618 11619 // Update thisMBB to fall through to newMBB 11620 thisMBB->addSuccessor(newMBB); 11621 11622 // newMBB jumps to newMBB and fall through to nextMBB 11623 newMBB->addSuccessor(nextMBB); 11624 newMBB->addSuccessor(newMBB); 11625 11626 DebugLoc dl = mInstr->getDebugLoc(); 11627 // Insert instructions into newMBB based on incoming instruction 11628 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 && 11629 "unexpected number of operands"); 11630 MachineOperand& destOper = mInstr->getOperand(0); 11631 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11632 int numArgs = mInstr->getNumOperands() - 1; 11633 for (int i=0; i < numArgs; ++i) 11634 argOpers[i] = &mInstr->getOperand(i+1); 11635 11636 // x86 address has 4 operands: base, index, scale, and displacement 11637 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11638 int valArgIndx = lastAddrIndx + 1; 11639 11640 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 11641 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1); 11642 for (int i=0; i <= lastAddrIndx; ++i) 11643 (*MIB).addOperand(*argOpers[i]); 11644 11645 // We only support register and immediate values 11646 assert((argOpers[valArgIndx]->isReg() || 11647 argOpers[valArgIndx]->isImm()) && 11648 "invalid operand"); 11649 11650 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 11651 if (argOpers[valArgIndx]->isReg()) 11652 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2); 11653 else 11654 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2); 11655 (*MIB).addOperand(*argOpers[valArgIndx]); 11656 11657 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 11658 MIB.addReg(t1); 11659 11660 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr)); 11661 MIB.addReg(t1); 11662 MIB.addReg(t2); 11663 11664 // Generate movc 11665 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 11666 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3); 11667 MIB.addReg(t2); 11668 MIB.addReg(t1); 11669 11670 // Cmp and exchange if none has modified the memory location 11671 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32)); 11672 for (int i=0; i <= lastAddrIndx; ++i) 11673 (*MIB).addOperand(*argOpers[i]); 11674 MIB.addReg(t3); 11675 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11676 (*MIB).setMemRefs(mInstr->memoperands_begin(), 11677 mInstr->memoperands_end()); 11678 11679 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 11680 MIB.addReg(X86::EAX); 11681 11682 // insert branch 11683 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11684 11685 mInstr->eraseFromParent(); // The pseudo instruction is gone now. 11686 return nextMBB; 11687 } 11688 11689 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8 11690 // or XMM0_V32I8 in AVX all of this code can be replaced with that 11691 // in the .td file. 11692 MachineBasicBlock * 11693 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB, 11694 unsigned numArgs, bool memArg) const { 11695 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) && 11696 "Target must have SSE4.2 or AVX features enabled"); 11697 11698 DebugLoc dl = MI->getDebugLoc(); 11699 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11700 unsigned Opc; 11701 if (!Subtarget->hasAVX()) { 11702 if (memArg) 11703 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm; 11704 else 11705 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr; 11706 } else { 11707 if (memArg) 11708 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm; 11709 else 11710 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr; 11711 } 11712 11713 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 11714 for (unsigned i = 0; i < numArgs; ++i) { 11715 MachineOperand &Op = MI->getOperand(i+1); 11716 if (!(Op.isReg() && Op.isImplicit())) 11717 MIB.addOperand(Op); 11718 } 11719 BuildMI(*BB, MI, dl, 11720 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr), 11721 MI->getOperand(0).getReg()) 11722 .addReg(X86::XMM0); 11723 11724 MI->eraseFromParent(); 11725 return BB; 11726 } 11727 11728 MachineBasicBlock * 11729 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const { 11730 DebugLoc dl = MI->getDebugLoc(); 11731 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11732 11733 // Address into RAX/EAX, other two args into ECX, EDX. 11734 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 11735 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 11736 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg); 11737 for (int i = 0; i < X86::AddrNumOperands; ++i) 11738 MIB.addOperand(MI->getOperand(i)); 11739 11740 unsigned ValOps = X86::AddrNumOperands; 11741 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 11742 .addReg(MI->getOperand(ValOps).getReg()); 11743 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX) 11744 .addReg(MI->getOperand(ValOps+1).getReg()); 11745 11746 // The instruction doesn't actually take any operands though. 11747 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr)); 11748 11749 MI->eraseFromParent(); // The pseudo is gone now. 11750 return BB; 11751 } 11752 11753 MachineBasicBlock * 11754 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const { 11755 DebugLoc dl = MI->getDebugLoc(); 11756 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11757 11758 // First arg in ECX, the second in EAX. 11759 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 11760 .addReg(MI->getOperand(0).getReg()); 11761 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX) 11762 .addReg(MI->getOperand(1).getReg()); 11763 11764 // The instruction doesn't actually take any operands though. 11765 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr)); 11766 11767 MI->eraseFromParent(); // The pseudo is gone now. 11768 return BB; 11769 } 11770 11771 MachineBasicBlock * 11772 X86TargetLowering::EmitVAARG64WithCustomInserter( 11773 MachineInstr *MI, 11774 MachineBasicBlock *MBB) const { 11775 // Emit va_arg instruction on X86-64. 11776 11777 // Operands to this pseudo-instruction: 11778 // 0 ) Output : destination address (reg) 11779 // 1-5) Input : va_list address (addr, i64mem) 11780 // 6 ) ArgSize : Size (in bytes) of vararg type 11781 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset 11782 // 8 ) Align : Alignment of type 11783 // 9 ) EFLAGS (implicit-def) 11784 11785 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!"); 11786 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands"); 11787 11788 unsigned DestReg = MI->getOperand(0).getReg(); 11789 MachineOperand &Base = MI->getOperand(1); 11790 MachineOperand &Scale = MI->getOperand(2); 11791 MachineOperand &Index = MI->getOperand(3); 11792 MachineOperand &Disp = MI->getOperand(4); 11793 MachineOperand &Segment = MI->getOperand(5); 11794 unsigned ArgSize = MI->getOperand(6).getImm(); 11795 unsigned ArgMode = MI->getOperand(7).getImm(); 11796 unsigned Align = MI->getOperand(8).getImm(); 11797 11798 // Memory Reference 11799 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"); 11800 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 11801 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 11802 11803 // Machine Information 11804 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11805 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 11806 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64); 11807 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32); 11808 DebugLoc DL = MI->getDebugLoc(); 11809 11810 // struct va_list { 11811 // i32 gp_offset 11812 // i32 fp_offset 11813 // i64 overflow_area (address) 11814 // i64 reg_save_area (address) 11815 // } 11816 // sizeof(va_list) = 24 11817 // alignment(va_list) = 8 11818 11819 unsigned TotalNumIntRegs = 6; 11820 unsigned TotalNumXMMRegs = 8; 11821 bool UseGPOffset = (ArgMode == 1); 11822 bool UseFPOffset = (ArgMode == 2); 11823 unsigned MaxOffset = TotalNumIntRegs * 8 + 11824 (UseFPOffset ? TotalNumXMMRegs * 16 : 0); 11825 11826 /* Align ArgSize to a multiple of 8 */ 11827 unsigned ArgSizeA8 = (ArgSize + 7) & ~7; 11828 bool NeedsAlign = (Align > 8); 11829 11830 MachineBasicBlock *thisMBB = MBB; 11831 MachineBasicBlock *overflowMBB; 11832 MachineBasicBlock *offsetMBB; 11833 MachineBasicBlock *endMBB; 11834 11835 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB 11836 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB 11837 unsigned OffsetReg = 0; 11838 11839 if (!UseGPOffset && !UseFPOffset) { 11840 // If we only pull from the overflow region, we don't create a branch. 11841 // We don't need to alter control flow. 11842 OffsetDestReg = 0; // unused 11843 OverflowDestReg = DestReg; 11844 11845 offsetMBB = NULL; 11846 overflowMBB = thisMBB; 11847 endMBB = thisMBB; 11848 } else { 11849 // First emit code to check if gp_offset (or fp_offset) is below the bound. 11850 // If so, pull the argument from reg_save_area. (branch to offsetMBB) 11851 // If not, pull from overflow_area. (branch to overflowMBB) 11852 // 11853 // thisMBB 11854 // | . 11855 // | . 11856 // offsetMBB overflowMBB 11857 // | . 11858 // | . 11859 // endMBB 11860 11861 // Registers for the PHI in endMBB 11862 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass); 11863 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass); 11864 11865 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11866 MachineFunction *MF = MBB->getParent(); 11867 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11868 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11869 endMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11870 11871 MachineFunction::iterator MBBIter = MBB; 11872 ++MBBIter; 11873 11874 // Insert the new basic blocks 11875 MF->insert(MBBIter, offsetMBB); 11876 MF->insert(MBBIter, overflowMBB); 11877 MF->insert(MBBIter, endMBB); 11878 11879 // Transfer the remainder of MBB and its successor edges to endMBB. 11880 endMBB->splice(endMBB->begin(), thisMBB, 11881 llvm::next(MachineBasicBlock::iterator(MI)), 11882 thisMBB->end()); 11883 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11884 11885 // Make offsetMBB and overflowMBB successors of thisMBB 11886 thisMBB->addSuccessor(offsetMBB); 11887 thisMBB->addSuccessor(overflowMBB); 11888 11889 // endMBB is a successor of both offsetMBB and overflowMBB 11890 offsetMBB->addSuccessor(endMBB); 11891 overflowMBB->addSuccessor(endMBB); 11892 11893 // Load the offset value into a register 11894 OffsetReg = MRI.createVirtualRegister(OffsetRegClass); 11895 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg) 11896 .addOperand(Base) 11897 .addOperand(Scale) 11898 .addOperand(Index) 11899 .addDisp(Disp, UseFPOffset ? 4 : 0) 11900 .addOperand(Segment) 11901 .setMemRefs(MMOBegin, MMOEnd); 11902 11903 // Check if there is enough room left to pull this argument. 11904 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri)) 11905 .addReg(OffsetReg) 11906 .addImm(MaxOffset + 8 - ArgSizeA8); 11907 11908 // Branch to "overflowMBB" if offset >= max 11909 // Fall through to "offsetMBB" otherwise 11910 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE))) 11911 .addMBB(overflowMBB); 11912 } 11913 11914 // In offsetMBB, emit code to use the reg_save_area. 11915 if (offsetMBB) { 11916 assert(OffsetReg != 0); 11917 11918 // Read the reg_save_area address. 11919 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass); 11920 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg) 11921 .addOperand(Base) 11922 .addOperand(Scale) 11923 .addOperand(Index) 11924 .addDisp(Disp, 16) 11925 .addOperand(Segment) 11926 .setMemRefs(MMOBegin, MMOEnd); 11927 11928 // Zero-extend the offset 11929 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass); 11930 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64) 11931 .addImm(0) 11932 .addReg(OffsetReg) 11933 .addImm(X86::sub_32bit); 11934 11935 // Add the offset to the reg_save_area to get the final address. 11936 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg) 11937 .addReg(OffsetReg64) 11938 .addReg(RegSaveReg); 11939 11940 // Compute the offset for the next argument 11941 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass); 11942 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg) 11943 .addReg(OffsetReg) 11944 .addImm(UseFPOffset ? 16 : 8); 11945 11946 // Store it back into the va_list. 11947 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr)) 11948 .addOperand(Base) 11949 .addOperand(Scale) 11950 .addOperand(Index) 11951 .addDisp(Disp, UseFPOffset ? 4 : 0) 11952 .addOperand(Segment) 11953 .addReg(NextOffsetReg) 11954 .setMemRefs(MMOBegin, MMOEnd); 11955 11956 // Jump to endMBB 11957 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4)) 11958 .addMBB(endMBB); 11959 } 11960 11961 // 11962 // Emit code to use overflow area 11963 // 11964 11965 // Load the overflow_area address into a register. 11966 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass); 11967 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg) 11968 .addOperand(Base) 11969 .addOperand(Scale) 11970 .addOperand(Index) 11971 .addDisp(Disp, 8) 11972 .addOperand(Segment) 11973 .setMemRefs(MMOBegin, MMOEnd); 11974 11975 // If we need to align it, do so. Otherwise, just copy the address 11976 // to OverflowDestReg. 11977 if (NeedsAlign) { 11978 // Align the overflow address 11979 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2"); 11980 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass); 11981 11982 // aligned_addr = (addr + (align-1)) & ~(align-1) 11983 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg) 11984 .addReg(OverflowAddrReg) 11985 .addImm(Align-1); 11986 11987 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg) 11988 .addReg(TmpReg) 11989 .addImm(~(uint64_t)(Align-1)); 11990 } else { 11991 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg) 11992 .addReg(OverflowAddrReg); 11993 } 11994 11995 // Compute the next overflow address after this argument. 11996 // (the overflow address should be kept 8-byte aligned) 11997 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass); 11998 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg) 11999 .addReg(OverflowDestReg) 12000 .addImm(ArgSizeA8); 12001 12002 // Store the new overflow address. 12003 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr)) 12004 .addOperand(Base) 12005 .addOperand(Scale) 12006 .addOperand(Index) 12007 .addDisp(Disp, 8) 12008 .addOperand(Segment) 12009 .addReg(NextAddrReg) 12010 .setMemRefs(MMOBegin, MMOEnd); 12011 12012 // If we branched, emit the PHI to the front of endMBB. 12013 if (offsetMBB) { 12014 BuildMI(*endMBB, endMBB->begin(), DL, 12015 TII->get(X86::PHI), DestReg) 12016 .addReg(OffsetDestReg).addMBB(offsetMBB) 12017 .addReg(OverflowDestReg).addMBB(overflowMBB); 12018 } 12019 12020 // Erase the pseudo instruction 12021 MI->eraseFromParent(); 12022 12023 return endMBB; 12024 } 12025 12026 MachineBasicBlock * 12027 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter( 12028 MachineInstr *MI, 12029 MachineBasicBlock *MBB) const { 12030 // Emit code to save XMM registers to the stack. The ABI says that the 12031 // number of registers to save is given in %al, so it's theoretically 12032 // possible to do an indirect jump trick to avoid saving all of them, 12033 // however this code takes a simpler approach and just executes all 12034 // of the stores if %al is non-zero. It's less code, and it's probably 12035 // easier on the hardware branch predictor, and stores aren't all that 12036 // expensive anyway. 12037 12038 // Create the new basic blocks. One block contains all the XMM stores, 12039 // and one block is the final destination regardless of whether any 12040 // stores were performed. 12041 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 12042 MachineFunction *F = MBB->getParent(); 12043 MachineFunction::iterator MBBIter = MBB; 12044 ++MBBIter; 12045 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB); 12046 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB); 12047 F->insert(MBBIter, XMMSaveMBB); 12048 F->insert(MBBIter, EndMBB); 12049 12050 // Transfer the remainder of MBB and its successor edges to EndMBB. 12051 EndMBB->splice(EndMBB->begin(), MBB, 12052 llvm::next(MachineBasicBlock::iterator(MI)), 12053 MBB->end()); 12054 EndMBB->transferSuccessorsAndUpdatePHIs(MBB); 12055 12056 // The original block will now fall through to the XMM save block. 12057 MBB->addSuccessor(XMMSaveMBB); 12058 // The XMMSaveMBB will fall through to the end block. 12059 XMMSaveMBB->addSuccessor(EndMBB); 12060 12061 // Now add the instructions. 12062 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12063 DebugLoc DL = MI->getDebugLoc(); 12064 12065 unsigned CountReg = MI->getOperand(0).getReg(); 12066 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm(); 12067 int64_t VarArgsFPOffset = MI->getOperand(2).getImm(); 12068 12069 if (!Subtarget->isTargetWin64()) { 12070 // If %al is 0, branch around the XMM save block. 12071 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg); 12072 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB); 12073 MBB->addSuccessor(EndMBB); 12074 } 12075 12076 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr; 12077 // In the XMM save block, save all the XMM argument registers. 12078 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) { 12079 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset; 12080 MachineMemOperand *MMO = 12081 F->getMachineMemOperand( 12082 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset), 12083 MachineMemOperand::MOStore, 12084 /*Size=*/16, /*Align=*/16); 12085 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc)) 12086 .addFrameIndex(RegSaveFrameIndex) 12087 .addImm(/*Scale=*/1) 12088 .addReg(/*IndexReg=*/0) 12089 .addImm(/*Disp=*/Offset) 12090 .addReg(/*Segment=*/0) 12091 .addReg(MI->getOperand(i).getReg()) 12092 .addMemOperand(MMO); 12093 } 12094 12095 MI->eraseFromParent(); // The pseudo instruction is gone now. 12096 12097 return EndMBB; 12098 } 12099 12100 MachineBasicBlock * 12101 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, 12102 MachineBasicBlock *BB) const { 12103 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12104 DebugLoc DL = MI->getDebugLoc(); 12105 12106 // To "insert" a SELECT_CC instruction, we actually have to insert the 12107 // diamond control-flow pattern. The incoming instruction knows the 12108 // destination vreg to set, the condition code register to branch on, the 12109 // true/false values to select between, and a branch opcode to use. 12110 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12111 MachineFunction::iterator It = BB; 12112 ++It; 12113 12114 // thisMBB: 12115 // ... 12116 // TrueVal = ... 12117 // cmpTY ccX, r1, r2 12118 // bCC copy1MBB 12119 // fallthrough --> copy0MBB 12120 MachineBasicBlock *thisMBB = BB; 12121 MachineFunction *F = BB->getParent(); 12122 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 12123 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12124 F->insert(It, copy0MBB); 12125 F->insert(It, sinkMBB); 12126 12127 // If the EFLAGS register isn't dead in the terminator, then claim that it's 12128 // live into the sink and copy blocks. 12129 if (!MI->killsRegister(X86::EFLAGS)) { 12130 copy0MBB->addLiveIn(X86::EFLAGS); 12131 sinkMBB->addLiveIn(X86::EFLAGS); 12132 } 12133 12134 // Transfer the remainder of BB and its successor edges to sinkMBB. 12135 sinkMBB->splice(sinkMBB->begin(), BB, 12136 llvm::next(MachineBasicBlock::iterator(MI)), 12137 BB->end()); 12138 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12139 12140 // Add the true and fallthrough blocks as its successors. 12141 BB->addSuccessor(copy0MBB); 12142 BB->addSuccessor(sinkMBB); 12143 12144 // Create the conditional branch instruction. 12145 unsigned Opc = 12146 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm()); 12147 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB); 12148 12149 // copy0MBB: 12150 // %FalseValue = ... 12151 // # fallthrough to sinkMBB 12152 copy0MBB->addSuccessor(sinkMBB); 12153 12154 // sinkMBB: 12155 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 12156 // ... 12157 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 12158 TII->get(X86::PHI), MI->getOperand(0).getReg()) 12159 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 12160 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 12161 12162 MI->eraseFromParent(); // The pseudo instruction is gone now. 12163 return sinkMBB; 12164 } 12165 12166 MachineBasicBlock * 12167 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB, 12168 bool Is64Bit) const { 12169 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12170 DebugLoc DL = MI->getDebugLoc(); 12171 MachineFunction *MF = BB->getParent(); 12172 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12173 12174 assert(EnableSegmentedStacks); 12175 12176 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS; 12177 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30; 12178 12179 // BB: 12180 // ... [Till the alloca] 12181 // If stacklet is not large enough, jump to mallocMBB 12182 // 12183 // bumpMBB: 12184 // Allocate by subtracting from RSP 12185 // Jump to continueMBB 12186 // 12187 // mallocMBB: 12188 // Allocate by call to runtime 12189 // 12190 // continueMBB: 12191 // ... 12192 // [rest of original BB] 12193 // 12194 12195 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12196 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12197 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12198 12199 MachineRegisterInfo &MRI = MF->getRegInfo(); 12200 const TargetRegisterClass *AddrRegClass = 12201 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32); 12202 12203 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass), 12204 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass), 12205 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass), 12206 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass), 12207 sizeVReg = MI->getOperand(1).getReg(), 12208 physSPReg = Is64Bit ? X86::RSP : X86::ESP; 12209 12210 MachineFunction::iterator MBBIter = BB; 12211 ++MBBIter; 12212 12213 MF->insert(MBBIter, bumpMBB); 12214 MF->insert(MBBIter, mallocMBB); 12215 MF->insert(MBBIter, continueMBB); 12216 12217 continueMBB->splice(continueMBB->begin(), BB, llvm::next 12218 (MachineBasicBlock::iterator(MI)), BB->end()); 12219 continueMBB->transferSuccessorsAndUpdatePHIs(BB); 12220 12221 // Add code to the main basic block to check if the stack limit has been hit, 12222 // and if so, jump to mallocMBB otherwise to bumpMBB. 12223 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg); 12224 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg) 12225 .addReg(tmpSPVReg).addReg(sizeVReg); 12226 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr)) 12227 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg) 12228 .addReg(SPLimitVReg); 12229 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB); 12230 12231 // bumpMBB simply decreases the stack pointer, since we know the current 12232 // stacklet has enough space. 12233 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg) 12234 .addReg(SPLimitVReg); 12235 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg) 12236 .addReg(SPLimitVReg); 12237 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 12238 12239 // Calls into a routine in libgcc to allocate more space from the heap. 12240 if (Is64Bit) { 12241 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI) 12242 .addReg(sizeVReg); 12243 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32)) 12244 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI); 12245 } else { 12246 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg) 12247 .addImm(12); 12248 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg); 12249 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32)) 12250 .addExternalSymbol("__morestack_allocate_stack_space"); 12251 } 12252 12253 if (!Is64Bit) 12254 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg) 12255 .addImm(16); 12256 12257 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg) 12258 .addReg(Is64Bit ? X86::RAX : X86::EAX); 12259 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 12260 12261 // Set up the CFG correctly. 12262 BB->addSuccessor(bumpMBB); 12263 BB->addSuccessor(mallocMBB); 12264 mallocMBB->addSuccessor(continueMBB); 12265 bumpMBB->addSuccessor(continueMBB); 12266 12267 // Take care of the PHI nodes. 12268 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI), 12269 MI->getOperand(0).getReg()) 12270 .addReg(mallocPtrVReg).addMBB(mallocMBB) 12271 .addReg(bumpSPPtrVReg).addMBB(bumpMBB); 12272 12273 // Delete the original pseudo instruction. 12274 MI->eraseFromParent(); 12275 12276 // And we're done. 12277 return continueMBB; 12278 } 12279 12280 MachineBasicBlock * 12281 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI, 12282 MachineBasicBlock *BB) const { 12283 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12284 DebugLoc DL = MI->getDebugLoc(); 12285 12286 assert(!Subtarget->isTargetEnvMacho()); 12287 12288 // The lowering is pretty easy: we're just emitting the call to _alloca. The 12289 // non-trivial part is impdef of ESP. 12290 12291 if (Subtarget->isTargetWin64()) { 12292 if (Subtarget->isTargetCygMing()) { 12293 // ___chkstk(Mingw64): 12294 // Clobbers R10, R11, RAX and EFLAGS. 12295 // Updates RSP. 12296 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 12297 .addExternalSymbol("___chkstk") 12298 .addReg(X86::RAX, RegState::Implicit) 12299 .addReg(X86::RSP, RegState::Implicit) 12300 .addReg(X86::RAX, RegState::Define | RegState::Implicit) 12301 .addReg(X86::RSP, RegState::Define | RegState::Implicit) 12302 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 12303 } else { 12304 // __chkstk(MSVCRT): does not update stack pointer. 12305 // Clobbers R10, R11 and EFLAGS. 12306 // FIXME: RAX(allocated size) might be reused and not killed. 12307 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 12308 .addExternalSymbol("__chkstk") 12309 .addReg(X86::RAX, RegState::Implicit) 12310 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 12311 // RAX has the offset to subtracted from RSP. 12312 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP) 12313 .addReg(X86::RSP) 12314 .addReg(X86::RAX); 12315 } 12316 } else { 12317 const char *StackProbeSymbol = 12318 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca"; 12319 12320 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32)) 12321 .addExternalSymbol(StackProbeSymbol) 12322 .addReg(X86::EAX, RegState::Implicit) 12323 .addReg(X86::ESP, RegState::Implicit) 12324 .addReg(X86::EAX, RegState::Define | RegState::Implicit) 12325 .addReg(X86::ESP, RegState::Define | RegState::Implicit) 12326 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 12327 } 12328 12329 MI->eraseFromParent(); // The pseudo instruction is gone now. 12330 return BB; 12331 } 12332 12333 MachineBasicBlock * 12334 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI, 12335 MachineBasicBlock *BB) const { 12336 // This is pretty easy. We're taking the value that we received from 12337 // our load from the relocation, sticking it in either RDI (x86-64) 12338 // or EAX and doing an indirect call. The return value will then 12339 // be in the normal return register. 12340 const X86InstrInfo *TII 12341 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo()); 12342 DebugLoc DL = MI->getDebugLoc(); 12343 MachineFunction *F = BB->getParent(); 12344 12345 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?"); 12346 assert(MI->getOperand(3).isGlobal() && "This should be a global"); 12347 12348 if (Subtarget->is64Bit()) { 12349 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 12350 TII->get(X86::MOV64rm), X86::RDI) 12351 .addReg(X86::RIP) 12352 .addImm(0).addReg(0) 12353 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 12354 MI->getOperand(3).getTargetFlags()) 12355 .addReg(0); 12356 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m)); 12357 addDirectMem(MIB, X86::RDI); 12358 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) { 12359 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 12360 TII->get(X86::MOV32rm), X86::EAX) 12361 .addReg(0) 12362 .addImm(0).addReg(0) 12363 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 12364 MI->getOperand(3).getTargetFlags()) 12365 .addReg(0); 12366 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 12367 addDirectMem(MIB, X86::EAX); 12368 } else { 12369 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 12370 TII->get(X86::MOV32rm), X86::EAX) 12371 .addReg(TII->getGlobalBaseReg(F)) 12372 .addImm(0).addReg(0) 12373 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 12374 MI->getOperand(3).getTargetFlags()) 12375 .addReg(0); 12376 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 12377 addDirectMem(MIB, X86::EAX); 12378 } 12379 12380 MI->eraseFromParent(); // The pseudo instruction is gone now. 12381 return BB; 12382 } 12383 12384 MachineBasicBlock * 12385 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 12386 MachineBasicBlock *BB) const { 12387 switch (MI->getOpcode()) { 12388 default: assert(0 && "Unexpected instr type to insert"); 12389 case X86::TAILJMPd64: 12390 case X86::TAILJMPr64: 12391 case X86::TAILJMPm64: 12392 assert(0 && "TAILJMP64 would not be touched here."); 12393 case X86::TCRETURNdi64: 12394 case X86::TCRETURNri64: 12395 case X86::TCRETURNmi64: 12396 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset. 12397 // On AMD64, additional defs should be added before register allocation. 12398 if (!Subtarget->isTargetWin64()) { 12399 MI->addRegisterDefined(X86::RSI); 12400 MI->addRegisterDefined(X86::RDI); 12401 MI->addRegisterDefined(X86::XMM6); 12402 MI->addRegisterDefined(X86::XMM7); 12403 MI->addRegisterDefined(X86::XMM8); 12404 MI->addRegisterDefined(X86::XMM9); 12405 MI->addRegisterDefined(X86::XMM10); 12406 MI->addRegisterDefined(X86::XMM11); 12407 MI->addRegisterDefined(X86::XMM12); 12408 MI->addRegisterDefined(X86::XMM13); 12409 MI->addRegisterDefined(X86::XMM14); 12410 MI->addRegisterDefined(X86::XMM15); 12411 } 12412 return BB; 12413 case X86::WIN_ALLOCA: 12414 return EmitLoweredWinAlloca(MI, BB); 12415 case X86::SEG_ALLOCA_32: 12416 return EmitLoweredSegAlloca(MI, BB, false); 12417 case X86::SEG_ALLOCA_64: 12418 return EmitLoweredSegAlloca(MI, BB, true); 12419 case X86::TLSCall_32: 12420 case X86::TLSCall_64: 12421 return EmitLoweredTLSCall(MI, BB); 12422 case X86::CMOV_GR8: 12423 case X86::CMOV_FR32: 12424 case X86::CMOV_FR64: 12425 case X86::CMOV_V4F32: 12426 case X86::CMOV_V2F64: 12427 case X86::CMOV_V2I64: 12428 case X86::CMOV_V8F32: 12429 case X86::CMOV_V4F64: 12430 case X86::CMOV_V4I64: 12431 case X86::CMOV_GR16: 12432 case X86::CMOV_GR32: 12433 case X86::CMOV_RFP32: 12434 case X86::CMOV_RFP64: 12435 case X86::CMOV_RFP80: 12436 return EmitLoweredSelect(MI, BB); 12437 12438 case X86::FP32_TO_INT16_IN_MEM: 12439 case X86::FP32_TO_INT32_IN_MEM: 12440 case X86::FP32_TO_INT64_IN_MEM: 12441 case X86::FP64_TO_INT16_IN_MEM: 12442 case X86::FP64_TO_INT32_IN_MEM: 12443 case X86::FP64_TO_INT64_IN_MEM: 12444 case X86::FP80_TO_INT16_IN_MEM: 12445 case X86::FP80_TO_INT32_IN_MEM: 12446 case X86::FP80_TO_INT64_IN_MEM: { 12447 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12448 DebugLoc DL = MI->getDebugLoc(); 12449 12450 // Change the floating point control register to use "round towards zero" 12451 // mode when truncating to an integer value. 12452 MachineFunction *F = BB->getParent(); 12453 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false); 12454 addFrameReference(BuildMI(*BB, MI, DL, 12455 TII->get(X86::FNSTCW16m)), CWFrameIdx); 12456 12457 // Load the old value of the high byte of the control word... 12458 unsigned OldCW = 12459 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass); 12460 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW), 12461 CWFrameIdx); 12462 12463 // Set the high part to be round to zero... 12464 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx) 12465 .addImm(0xC7F); 12466 12467 // Reload the modified control word now... 12468 addFrameReference(BuildMI(*BB, MI, DL, 12469 TII->get(X86::FLDCW16m)), CWFrameIdx); 12470 12471 // Restore the memory image of control word to original value 12472 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx) 12473 .addReg(OldCW); 12474 12475 // Get the X86 opcode to use. 12476 unsigned Opc; 12477 switch (MI->getOpcode()) { 12478 default: llvm_unreachable("illegal opcode!"); 12479 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break; 12480 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break; 12481 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break; 12482 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break; 12483 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break; 12484 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break; 12485 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break; 12486 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break; 12487 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break; 12488 } 12489 12490 X86AddressMode AM; 12491 MachineOperand &Op = MI->getOperand(0); 12492 if (Op.isReg()) { 12493 AM.BaseType = X86AddressMode::RegBase; 12494 AM.Base.Reg = Op.getReg(); 12495 } else { 12496 AM.BaseType = X86AddressMode::FrameIndexBase; 12497 AM.Base.FrameIndex = Op.getIndex(); 12498 } 12499 Op = MI->getOperand(1); 12500 if (Op.isImm()) 12501 AM.Scale = Op.getImm(); 12502 Op = MI->getOperand(2); 12503 if (Op.isImm()) 12504 AM.IndexReg = Op.getImm(); 12505 Op = MI->getOperand(3); 12506 if (Op.isGlobal()) { 12507 AM.GV = Op.getGlobal(); 12508 } else { 12509 AM.Disp = Op.getImm(); 12510 } 12511 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM) 12512 .addReg(MI->getOperand(X86::AddrNumOperands).getReg()); 12513 12514 // Reload the original control word now. 12515 addFrameReference(BuildMI(*BB, MI, DL, 12516 TII->get(X86::FLDCW16m)), CWFrameIdx); 12517 12518 MI->eraseFromParent(); // The pseudo instruction is gone now. 12519 return BB; 12520 } 12521 // String/text processing lowering. 12522 case X86::PCMPISTRM128REG: 12523 case X86::VPCMPISTRM128REG: 12524 return EmitPCMP(MI, BB, 3, false /* in-mem */); 12525 case X86::PCMPISTRM128MEM: 12526 case X86::VPCMPISTRM128MEM: 12527 return EmitPCMP(MI, BB, 3, true /* in-mem */); 12528 case X86::PCMPESTRM128REG: 12529 case X86::VPCMPESTRM128REG: 12530 return EmitPCMP(MI, BB, 5, false /* in mem */); 12531 case X86::PCMPESTRM128MEM: 12532 case X86::VPCMPESTRM128MEM: 12533 return EmitPCMP(MI, BB, 5, true /* in mem */); 12534 12535 // Thread synchronization. 12536 case X86::MONITOR: 12537 return EmitMonitor(MI, BB); 12538 case X86::MWAIT: 12539 return EmitMwait(MI, BB); 12540 12541 // Atomic Lowering. 12542 case X86::ATOMAND32: 12543 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 12544 X86::AND32ri, X86::MOV32rm, 12545 X86::LCMPXCHG32, 12546 X86::NOT32r, X86::EAX, 12547 X86::GR32RegisterClass); 12548 case X86::ATOMOR32: 12549 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 12550 X86::OR32ri, X86::MOV32rm, 12551 X86::LCMPXCHG32, 12552 X86::NOT32r, X86::EAX, 12553 X86::GR32RegisterClass); 12554 case X86::ATOMXOR32: 12555 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr, 12556 X86::XOR32ri, X86::MOV32rm, 12557 X86::LCMPXCHG32, 12558 X86::NOT32r, X86::EAX, 12559 X86::GR32RegisterClass); 12560 case X86::ATOMNAND32: 12561 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 12562 X86::AND32ri, X86::MOV32rm, 12563 X86::LCMPXCHG32, 12564 X86::NOT32r, X86::EAX, 12565 X86::GR32RegisterClass, true); 12566 case X86::ATOMMIN32: 12567 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr); 12568 case X86::ATOMMAX32: 12569 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr); 12570 case X86::ATOMUMIN32: 12571 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr); 12572 case X86::ATOMUMAX32: 12573 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr); 12574 12575 case X86::ATOMAND16: 12576 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 12577 X86::AND16ri, X86::MOV16rm, 12578 X86::LCMPXCHG16, 12579 X86::NOT16r, X86::AX, 12580 X86::GR16RegisterClass); 12581 case X86::ATOMOR16: 12582 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 12583 X86::OR16ri, X86::MOV16rm, 12584 X86::LCMPXCHG16, 12585 X86::NOT16r, X86::AX, 12586 X86::GR16RegisterClass); 12587 case X86::ATOMXOR16: 12588 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr, 12589 X86::XOR16ri, X86::MOV16rm, 12590 X86::LCMPXCHG16, 12591 X86::NOT16r, X86::AX, 12592 X86::GR16RegisterClass); 12593 case X86::ATOMNAND16: 12594 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 12595 X86::AND16ri, X86::MOV16rm, 12596 X86::LCMPXCHG16, 12597 X86::NOT16r, X86::AX, 12598 X86::GR16RegisterClass, true); 12599 case X86::ATOMMIN16: 12600 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr); 12601 case X86::ATOMMAX16: 12602 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr); 12603 case X86::ATOMUMIN16: 12604 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr); 12605 case X86::ATOMUMAX16: 12606 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr); 12607 12608 case X86::ATOMAND8: 12609 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 12610 X86::AND8ri, X86::MOV8rm, 12611 X86::LCMPXCHG8, 12612 X86::NOT8r, X86::AL, 12613 X86::GR8RegisterClass); 12614 case X86::ATOMOR8: 12615 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 12616 X86::OR8ri, X86::MOV8rm, 12617 X86::LCMPXCHG8, 12618 X86::NOT8r, X86::AL, 12619 X86::GR8RegisterClass); 12620 case X86::ATOMXOR8: 12621 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr, 12622 X86::XOR8ri, X86::MOV8rm, 12623 X86::LCMPXCHG8, 12624 X86::NOT8r, X86::AL, 12625 X86::GR8RegisterClass); 12626 case X86::ATOMNAND8: 12627 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 12628 X86::AND8ri, X86::MOV8rm, 12629 X86::LCMPXCHG8, 12630 X86::NOT8r, X86::AL, 12631 X86::GR8RegisterClass, true); 12632 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way. 12633 // This group is for 64-bit host. 12634 case X86::ATOMAND64: 12635 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 12636 X86::AND64ri32, X86::MOV64rm, 12637 X86::LCMPXCHG64, 12638 X86::NOT64r, X86::RAX, 12639 X86::GR64RegisterClass); 12640 case X86::ATOMOR64: 12641 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 12642 X86::OR64ri32, X86::MOV64rm, 12643 X86::LCMPXCHG64, 12644 X86::NOT64r, X86::RAX, 12645 X86::GR64RegisterClass); 12646 case X86::ATOMXOR64: 12647 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr, 12648 X86::XOR64ri32, X86::MOV64rm, 12649 X86::LCMPXCHG64, 12650 X86::NOT64r, X86::RAX, 12651 X86::GR64RegisterClass); 12652 case X86::ATOMNAND64: 12653 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 12654 X86::AND64ri32, X86::MOV64rm, 12655 X86::LCMPXCHG64, 12656 X86::NOT64r, X86::RAX, 12657 X86::GR64RegisterClass, true); 12658 case X86::ATOMMIN64: 12659 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr); 12660 case X86::ATOMMAX64: 12661 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr); 12662 case X86::ATOMUMIN64: 12663 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr); 12664 case X86::ATOMUMAX64: 12665 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr); 12666 12667 // This group does 64-bit operations on a 32-bit host. 12668 case X86::ATOMAND6432: 12669 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12670 X86::AND32rr, X86::AND32rr, 12671 X86::AND32ri, X86::AND32ri, 12672 false); 12673 case X86::ATOMOR6432: 12674 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12675 X86::OR32rr, X86::OR32rr, 12676 X86::OR32ri, X86::OR32ri, 12677 false); 12678 case X86::ATOMXOR6432: 12679 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12680 X86::XOR32rr, X86::XOR32rr, 12681 X86::XOR32ri, X86::XOR32ri, 12682 false); 12683 case X86::ATOMNAND6432: 12684 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12685 X86::AND32rr, X86::AND32rr, 12686 X86::AND32ri, X86::AND32ri, 12687 true); 12688 case X86::ATOMADD6432: 12689 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12690 X86::ADD32rr, X86::ADC32rr, 12691 X86::ADD32ri, X86::ADC32ri, 12692 false); 12693 case X86::ATOMSUB6432: 12694 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12695 X86::SUB32rr, X86::SBB32rr, 12696 X86::SUB32ri, X86::SBB32ri, 12697 false); 12698 case X86::ATOMSWAP6432: 12699 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12700 X86::MOV32rr, X86::MOV32rr, 12701 X86::MOV32ri, X86::MOV32ri, 12702 false); 12703 case X86::VASTART_SAVE_XMM_REGS: 12704 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB); 12705 12706 case X86::VAARG_64: 12707 return EmitVAARG64WithCustomInserter(MI, BB); 12708 } 12709 } 12710 12711 //===----------------------------------------------------------------------===// 12712 // X86 Optimization Hooks 12713 //===----------------------------------------------------------------------===// 12714 12715 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 12716 const APInt &Mask, 12717 APInt &KnownZero, 12718 APInt &KnownOne, 12719 const SelectionDAG &DAG, 12720 unsigned Depth) const { 12721 unsigned Opc = Op.getOpcode(); 12722 assert((Opc >= ISD::BUILTIN_OP_END || 12723 Opc == ISD::INTRINSIC_WO_CHAIN || 12724 Opc == ISD::INTRINSIC_W_CHAIN || 12725 Opc == ISD::INTRINSIC_VOID) && 12726 "Should use MaskedValueIsZero if you don't know whether Op" 12727 " is a target node!"); 12728 12729 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything. 12730 switch (Opc) { 12731 default: break; 12732 case X86ISD::ADD: 12733 case X86ISD::SUB: 12734 case X86ISD::ADC: 12735 case X86ISD::SBB: 12736 case X86ISD::SMUL: 12737 case X86ISD::UMUL: 12738 case X86ISD::INC: 12739 case X86ISD::DEC: 12740 case X86ISD::OR: 12741 case X86ISD::XOR: 12742 case X86ISD::AND: 12743 // These nodes' second result is a boolean. 12744 if (Op.getResNo() == 0) 12745 break; 12746 // Fallthrough 12747 case X86ISD::SETCC: 12748 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(), 12749 Mask.getBitWidth() - 1); 12750 break; 12751 case ISD::INTRINSIC_WO_CHAIN: { 12752 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12753 unsigned NumLoBits = 0; 12754 switch (IntId) { 12755 default: break; 12756 case Intrinsic::x86_sse_movmsk_ps: 12757 case Intrinsic::x86_avx_movmsk_ps_256: 12758 case Intrinsic::x86_sse2_movmsk_pd: 12759 case Intrinsic::x86_avx_movmsk_pd_256: 12760 case Intrinsic::x86_mmx_pmovmskb: 12761 case Intrinsic::x86_sse2_pmovmskb_128: { 12762 // High bits of movmskp{s|d}, pmovmskb are known zero. 12763 switch (IntId) { 12764 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break; 12765 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break; 12766 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break; 12767 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break; 12768 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break; 12769 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break; 12770 } 12771 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(), 12772 Mask.getBitWidth() - NumLoBits); 12773 break; 12774 } 12775 } 12776 break; 12777 } 12778 } 12779 } 12780 12781 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 12782 unsigned Depth) const { 12783 // SETCC_CARRY sets the dest to ~0 for true or 0 for false. 12784 if (Op.getOpcode() == X86ISD::SETCC_CARRY) 12785 return Op.getValueType().getScalarType().getSizeInBits(); 12786 12787 // Fallback case. 12788 return 1; 12789 } 12790 12791 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 12792 /// node is a GlobalAddress + offset. 12793 bool X86TargetLowering::isGAPlusOffset(SDNode *N, 12794 const GlobalValue* &GA, 12795 int64_t &Offset) const { 12796 if (N->getOpcode() == X86ISD::Wrapper) { 12797 if (isa<GlobalAddressSDNode>(N->getOperand(0))) { 12798 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal(); 12799 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset(); 12800 return true; 12801 } 12802 } 12803 return TargetLowering::isGAPlusOffset(N, GA, Offset); 12804 } 12805 12806 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the 12807 /// same as extracting the high 128-bit part of 256-bit vector and then 12808 /// inserting the result into the low part of a new 256-bit vector 12809 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) { 12810 EVT VT = SVOp->getValueType(0); 12811 int NumElems = VT.getVectorNumElements(); 12812 12813 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 12814 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j) 12815 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 12816 SVOp->getMaskElt(j) >= 0) 12817 return false; 12818 12819 return true; 12820 } 12821 12822 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the 12823 /// same as extracting the low 128-bit part of 256-bit vector and then 12824 /// inserting the result into the high part of a new 256-bit vector 12825 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) { 12826 EVT VT = SVOp->getValueType(0); 12827 int NumElems = VT.getVectorNumElements(); 12828 12829 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 12830 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j) 12831 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 12832 SVOp->getMaskElt(j) >= 0) 12833 return false; 12834 12835 return true; 12836 } 12837 12838 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors. 12839 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG, 12840 TargetLowering::DAGCombinerInfo &DCI) { 12841 DebugLoc dl = N->getDebugLoc(); 12842 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 12843 SDValue V1 = SVOp->getOperand(0); 12844 SDValue V2 = SVOp->getOperand(1); 12845 EVT VT = SVOp->getValueType(0); 12846 int NumElems = VT.getVectorNumElements(); 12847 12848 if (V1.getOpcode() == ISD::CONCAT_VECTORS && 12849 V2.getOpcode() == ISD::CONCAT_VECTORS) { 12850 // 12851 // 0,0,0,... 12852 // | 12853 // V UNDEF BUILD_VECTOR UNDEF 12854 // \ / \ / 12855 // CONCAT_VECTOR CONCAT_VECTOR 12856 // \ / 12857 // \ / 12858 // RESULT: V + zero extended 12859 // 12860 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR || 12861 V2.getOperand(1).getOpcode() != ISD::UNDEF || 12862 V1.getOperand(1).getOpcode() != ISD::UNDEF) 12863 return SDValue(); 12864 12865 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode())) 12866 return SDValue(); 12867 12868 // To match the shuffle mask, the first half of the mask should 12869 // be exactly the first vector, and all the rest a splat with the 12870 // first element of the second one. 12871 for (int i = 0; i < NumElems/2; ++i) 12872 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) || 12873 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems)) 12874 return SDValue(); 12875 12876 // Emit a zeroed vector and insert the desired subvector on its 12877 // first half. 12878 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl); 12879 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 12880 DAG.getConstant(0, MVT::i32), DAG, dl); 12881 return DCI.CombineTo(N, InsV); 12882 } 12883 12884 //===--------------------------------------------------------------------===// 12885 // Combine some shuffles into subvector extracts and inserts: 12886 // 12887 12888 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 12889 if (isShuffleHigh128VectorInsertLow(SVOp)) { 12890 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32), 12891 DAG, dl); 12892 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), 12893 V, DAG.getConstant(0, MVT::i32), DAG, dl); 12894 return DCI.CombineTo(N, InsV); 12895 } 12896 12897 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 12898 if (isShuffleLow128VectorInsertHigh(SVOp)) { 12899 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl); 12900 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), 12901 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl); 12902 return DCI.CombineTo(N, InsV); 12903 } 12904 12905 return SDValue(); 12906 } 12907 12908 /// PerformShuffleCombine - Performs several different shuffle combines. 12909 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG, 12910 TargetLowering::DAGCombinerInfo &DCI, 12911 const X86Subtarget *Subtarget) { 12912 DebugLoc dl = N->getDebugLoc(); 12913 EVT VT = N->getValueType(0); 12914 12915 // Don't create instructions with illegal types after legalize types has run. 12916 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12917 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType())) 12918 return SDValue(); 12919 12920 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode 12921 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 && 12922 N->getOpcode() == ISD::VECTOR_SHUFFLE) 12923 return PerformShuffleCombine256(N, DAG, DCI); 12924 12925 // Only handle 128 wide vector from here on. 12926 if (VT.getSizeInBits() != 128) 12927 return SDValue(); 12928 12929 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3, 12930 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are 12931 // consecutive, non-overlapping, and in the right order. 12932 SmallVector<SDValue, 16> Elts; 12933 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 12934 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0)); 12935 12936 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG); 12937 } 12938 12939 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index 12940 /// generation and convert it from being a bunch of shuffles and extracts 12941 /// to a simple store and scalar loads to extract the elements. 12942 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG, 12943 const TargetLowering &TLI) { 12944 SDValue InputVector = N->getOperand(0); 12945 12946 // Only operate on vectors of 4 elements, where the alternative shuffling 12947 // gets to be more expensive. 12948 if (InputVector.getValueType() != MVT::v4i32) 12949 return SDValue(); 12950 12951 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a 12952 // single use which is a sign-extend or zero-extend, and all elements are 12953 // used. 12954 SmallVector<SDNode *, 4> Uses; 12955 unsigned ExtractedElements = 0; 12956 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(), 12957 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) { 12958 if (UI.getUse().getResNo() != InputVector.getResNo()) 12959 return SDValue(); 12960 12961 SDNode *Extract = *UI; 12962 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12963 return SDValue(); 12964 12965 if (Extract->getValueType(0) != MVT::i32) 12966 return SDValue(); 12967 if (!Extract->hasOneUse()) 12968 return SDValue(); 12969 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND && 12970 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND) 12971 return SDValue(); 12972 if (!isa<ConstantSDNode>(Extract->getOperand(1))) 12973 return SDValue(); 12974 12975 // Record which element was extracted. 12976 ExtractedElements |= 12977 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue(); 12978 12979 Uses.push_back(Extract); 12980 } 12981 12982 // If not all the elements were used, this may not be worthwhile. 12983 if (ExtractedElements != 15) 12984 return SDValue(); 12985 12986 // Ok, we've now decided to do the transformation. 12987 DebugLoc dl = InputVector.getDebugLoc(); 12988 12989 // Store the value to a temporary stack slot. 12990 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType()); 12991 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, 12992 MachinePointerInfo(), false, false, 0); 12993 12994 // Replace each use (extract) with a load of the appropriate element. 12995 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(), 12996 UE = Uses.end(); UI != UE; ++UI) { 12997 SDNode *Extract = *UI; 12998 12999 // cOMpute the element's address. 13000 SDValue Idx = Extract->getOperand(1); 13001 unsigned EltSize = 13002 InputVector.getValueType().getVectorElementType().getSizeInBits()/8; 13003 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(); 13004 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy()); 13005 13006 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 13007 StackPtr, OffsetVal); 13008 13009 // Load the scalar. 13010 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, 13011 ScalarAddr, MachinePointerInfo(), 13012 false, false, false, 0); 13013 13014 // Replace the exact with the load. 13015 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar); 13016 } 13017 13018 // The replacement was made in place; don't return anything. 13019 return SDValue(); 13020 } 13021 13022 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT 13023 /// nodes. 13024 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG, 13025 const X86Subtarget *Subtarget) { 13026 DebugLoc DL = N->getDebugLoc(); 13027 SDValue Cond = N->getOperand(0); 13028 // Get the LHS/RHS of the select. 13029 SDValue LHS = N->getOperand(1); 13030 SDValue RHS = N->getOperand(2); 13031 EVT VT = LHS.getValueType(); 13032 13033 // If we have SSE[12] support, try to form min/max nodes. SSE min/max 13034 // instructions match the semantics of the common C idiom x<y?x:y but not 13035 // x<=y?x:y, because of how they handle negative zero (which can be 13036 // ignored in unsafe-math mode). 13037 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() && 13038 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 13039 (Subtarget->hasXMMInt() || 13040 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) { 13041 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 13042 13043 unsigned Opcode = 0; 13044 // Check for x CC y ? x : y. 13045 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 13046 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 13047 switch (CC) { 13048 default: break; 13049 case ISD::SETULT: 13050 // Converting this to a min would handle NaNs incorrectly, and swapping 13051 // the operands would cause it to handle comparisons between positive 13052 // and negative zero incorrectly. 13053 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 13054 if (!UnsafeFPMath && 13055 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 13056 break; 13057 std::swap(LHS, RHS); 13058 } 13059 Opcode = X86ISD::FMIN; 13060 break; 13061 case ISD::SETOLE: 13062 // Converting this to a min would handle comparisons between positive 13063 // and negative zero incorrectly. 13064 if (!UnsafeFPMath && 13065 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 13066 break; 13067 Opcode = X86ISD::FMIN; 13068 break; 13069 case ISD::SETULE: 13070 // Converting this to a min would handle both negative zeros and NaNs 13071 // incorrectly, but we can swap the operands to fix both. 13072 std::swap(LHS, RHS); 13073 case ISD::SETOLT: 13074 case ISD::SETLT: 13075 case ISD::SETLE: 13076 Opcode = X86ISD::FMIN; 13077 break; 13078 13079 case ISD::SETOGE: 13080 // Converting this to a max would handle comparisons between positive 13081 // and negative zero incorrectly. 13082 if (!UnsafeFPMath && 13083 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 13084 break; 13085 Opcode = X86ISD::FMAX; 13086 break; 13087 case ISD::SETUGT: 13088 // Converting this to a max would handle NaNs incorrectly, and swapping 13089 // the operands would cause it to handle comparisons between positive 13090 // and negative zero incorrectly. 13091 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 13092 if (!UnsafeFPMath && 13093 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 13094 break; 13095 std::swap(LHS, RHS); 13096 } 13097 Opcode = X86ISD::FMAX; 13098 break; 13099 case ISD::SETUGE: 13100 // Converting this to a max would handle both negative zeros and NaNs 13101 // incorrectly, but we can swap the operands to fix both. 13102 std::swap(LHS, RHS); 13103 case ISD::SETOGT: 13104 case ISD::SETGT: 13105 case ISD::SETGE: 13106 Opcode = X86ISD::FMAX; 13107 break; 13108 } 13109 // Check for x CC y ? y : x -- a min/max with reversed arms. 13110 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 13111 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 13112 switch (CC) { 13113 default: break; 13114 case ISD::SETOGE: 13115 // Converting this to a min would handle comparisons between positive 13116 // and negative zero incorrectly, and swapping the operands would 13117 // cause it to handle NaNs incorrectly. 13118 if (!UnsafeFPMath && 13119 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) { 13120 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 13121 break; 13122 std::swap(LHS, RHS); 13123 } 13124 Opcode = X86ISD::FMIN; 13125 break; 13126 case ISD::SETUGT: 13127 // Converting this to a min would handle NaNs incorrectly. 13128 if (!UnsafeFPMath && 13129 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) 13130 break; 13131 Opcode = X86ISD::FMIN; 13132 break; 13133 case ISD::SETUGE: 13134 // Converting this to a min would handle both negative zeros and NaNs 13135 // incorrectly, but we can swap the operands to fix both. 13136 std::swap(LHS, RHS); 13137 case ISD::SETOGT: 13138 case ISD::SETGT: 13139 case ISD::SETGE: 13140 Opcode = X86ISD::FMIN; 13141 break; 13142 13143 case ISD::SETULT: 13144 // Converting this to a max would handle NaNs incorrectly. 13145 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 13146 break; 13147 Opcode = X86ISD::FMAX; 13148 break; 13149 case ISD::SETOLE: 13150 // Converting this to a max would handle comparisons between positive 13151 // and negative zero incorrectly, and swapping the operands would 13152 // cause it to handle NaNs incorrectly. 13153 if (!UnsafeFPMath && 13154 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 13155 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 13156 break; 13157 std::swap(LHS, RHS); 13158 } 13159 Opcode = X86ISD::FMAX; 13160 break; 13161 case ISD::SETULE: 13162 // Converting this to a max would handle both negative zeros and NaNs 13163 // incorrectly, but we can swap the operands to fix both. 13164 std::swap(LHS, RHS); 13165 case ISD::SETOLT: 13166 case ISD::SETLT: 13167 case ISD::SETLE: 13168 Opcode = X86ISD::FMAX; 13169 break; 13170 } 13171 } 13172 13173 if (Opcode) 13174 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS); 13175 } 13176 13177 // If this is a select between two integer constants, try to do some 13178 // optimizations. 13179 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) { 13180 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS)) 13181 // Don't do this for crazy integer types. 13182 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) { 13183 // If this is efficiently invertible, canonicalize the LHSC/RHSC values 13184 // so that TrueC (the true value) is larger than FalseC. 13185 bool NeedsCondInvert = false; 13186 13187 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) && 13188 // Efficiently invertible. 13189 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible. 13190 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible. 13191 isa<ConstantSDNode>(Cond.getOperand(1))))) { 13192 NeedsCondInvert = true; 13193 std::swap(TrueC, FalseC); 13194 } 13195 13196 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0. 13197 if (FalseC->getAPIntValue() == 0 && 13198 TrueC->getAPIntValue().isPowerOf2()) { 13199 if (NeedsCondInvert) // Invert the condition if needed. 13200 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 13201 DAG.getConstant(1, Cond.getValueType())); 13202 13203 // Zero extend the condition if needed. 13204 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond); 13205 13206 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 13207 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond, 13208 DAG.getConstant(ShAmt, MVT::i8)); 13209 } 13210 13211 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. 13212 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 13213 if (NeedsCondInvert) // Invert the condition if needed. 13214 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 13215 DAG.getConstant(1, Cond.getValueType())); 13216 13217 // Zero extend the condition if needed. 13218 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 13219 FalseC->getValueType(0), Cond); 13220 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13221 SDValue(FalseC, 0)); 13222 } 13223 13224 // Optimize cases that will turn into an LEA instruction. This requires 13225 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 13226 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 13227 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 13228 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 13229 13230 bool isFastMultiplier = false; 13231 if (Diff < 10) { 13232 switch ((unsigned char)Diff) { 13233 default: break; 13234 case 1: // result = add base, cond 13235 case 2: // result = lea base( , cond*2) 13236 case 3: // result = lea base(cond, cond*2) 13237 case 4: // result = lea base( , cond*4) 13238 case 5: // result = lea base(cond, cond*4) 13239 case 8: // result = lea base( , cond*8) 13240 case 9: // result = lea base(cond, cond*8) 13241 isFastMultiplier = true; 13242 break; 13243 } 13244 } 13245 13246 if (isFastMultiplier) { 13247 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 13248 if (NeedsCondInvert) // Invert the condition if needed. 13249 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 13250 DAG.getConstant(1, Cond.getValueType())); 13251 13252 // Zero extend the condition if needed. 13253 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 13254 Cond); 13255 // Scale the condition by the difference. 13256 if (Diff != 1) 13257 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 13258 DAG.getConstant(Diff, Cond.getValueType())); 13259 13260 // Add the base if non-zero. 13261 if (FalseC->getAPIntValue() != 0) 13262 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13263 SDValue(FalseC, 0)); 13264 return Cond; 13265 } 13266 } 13267 } 13268 } 13269 13270 return SDValue(); 13271 } 13272 13273 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL] 13274 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG, 13275 TargetLowering::DAGCombinerInfo &DCI) { 13276 DebugLoc DL = N->getDebugLoc(); 13277 13278 // If the flag operand isn't dead, don't touch this CMOV. 13279 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty()) 13280 return SDValue(); 13281 13282 SDValue FalseOp = N->getOperand(0); 13283 SDValue TrueOp = N->getOperand(1); 13284 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2); 13285 SDValue Cond = N->getOperand(3); 13286 if (CC == X86::COND_E || CC == X86::COND_NE) { 13287 switch (Cond.getOpcode()) { 13288 default: break; 13289 case X86ISD::BSR: 13290 case X86ISD::BSF: 13291 // If operand of BSR / BSF are proven never zero, then ZF cannot be set. 13292 if (DAG.isKnownNeverZero(Cond.getOperand(0))) 13293 return (CC == X86::COND_E) ? FalseOp : TrueOp; 13294 } 13295 } 13296 13297 // If this is a select between two integer constants, try to do some 13298 // optimizations. Note that the operands are ordered the opposite of SELECT 13299 // operands. 13300 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) { 13301 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) { 13302 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is 13303 // larger than FalseC (the false value). 13304 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) { 13305 CC = X86::GetOppositeBranchCondition(CC); 13306 std::swap(TrueC, FalseC); 13307 } 13308 13309 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0. 13310 // This is efficient for any integer data type (including i8/i16) and 13311 // shift amount. 13312 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) { 13313 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 13314 DAG.getConstant(CC, MVT::i8), Cond); 13315 13316 // Zero extend the condition if needed. 13317 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond); 13318 13319 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 13320 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond, 13321 DAG.getConstant(ShAmt, MVT::i8)); 13322 if (N->getNumValues() == 2) // Dead flag value? 13323 return DCI.CombineTo(N, Cond, SDValue()); 13324 return Cond; 13325 } 13326 13327 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient 13328 // for any integer data type, including i8/i16. 13329 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 13330 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 13331 DAG.getConstant(CC, MVT::i8), Cond); 13332 13333 // Zero extend the condition if needed. 13334 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 13335 FalseC->getValueType(0), Cond); 13336 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13337 SDValue(FalseC, 0)); 13338 13339 if (N->getNumValues() == 2) // Dead flag value? 13340 return DCI.CombineTo(N, Cond, SDValue()); 13341 return Cond; 13342 } 13343 13344 // Optimize cases that will turn into an LEA instruction. This requires 13345 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 13346 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 13347 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 13348 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 13349 13350 bool isFastMultiplier = false; 13351 if (Diff < 10) { 13352 switch ((unsigned char)Diff) { 13353 default: break; 13354 case 1: // result = add base, cond 13355 case 2: // result = lea base( , cond*2) 13356 case 3: // result = lea base(cond, cond*2) 13357 case 4: // result = lea base( , cond*4) 13358 case 5: // result = lea base(cond, cond*4) 13359 case 8: // result = lea base( , cond*8) 13360 case 9: // result = lea base(cond, cond*8) 13361 isFastMultiplier = true; 13362 break; 13363 } 13364 } 13365 13366 if (isFastMultiplier) { 13367 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 13368 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 13369 DAG.getConstant(CC, MVT::i8), Cond); 13370 // Zero extend the condition if needed. 13371 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 13372 Cond); 13373 // Scale the condition by the difference. 13374 if (Diff != 1) 13375 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 13376 DAG.getConstant(Diff, Cond.getValueType())); 13377 13378 // Add the base if non-zero. 13379 if (FalseC->getAPIntValue() != 0) 13380 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13381 SDValue(FalseC, 0)); 13382 if (N->getNumValues() == 2) // Dead flag value? 13383 return DCI.CombineTo(N, Cond, SDValue()); 13384 return Cond; 13385 } 13386 } 13387 } 13388 } 13389 return SDValue(); 13390 } 13391 13392 13393 /// PerformMulCombine - Optimize a single multiply with constant into two 13394 /// in order to implement it with two cheaper instructions, e.g. 13395 /// LEA + SHL, LEA + LEA. 13396 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG, 13397 TargetLowering::DAGCombinerInfo &DCI) { 13398 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13399 return SDValue(); 13400 13401 EVT VT = N->getValueType(0); 13402 if (VT != MVT::i64) 13403 return SDValue(); 13404 13405 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13406 if (!C) 13407 return SDValue(); 13408 uint64_t MulAmt = C->getZExtValue(); 13409 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9) 13410 return SDValue(); 13411 13412 uint64_t MulAmt1 = 0; 13413 uint64_t MulAmt2 = 0; 13414 if ((MulAmt % 9) == 0) { 13415 MulAmt1 = 9; 13416 MulAmt2 = MulAmt / 9; 13417 } else if ((MulAmt % 5) == 0) { 13418 MulAmt1 = 5; 13419 MulAmt2 = MulAmt / 5; 13420 } else if ((MulAmt % 3) == 0) { 13421 MulAmt1 = 3; 13422 MulAmt2 = MulAmt / 3; 13423 } 13424 if (MulAmt2 && 13425 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){ 13426 DebugLoc DL = N->getDebugLoc(); 13427 13428 if (isPowerOf2_64(MulAmt2) && 13429 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD)) 13430 // If second multiplifer is pow2, issue it first. We want the multiply by 13431 // 3, 5, or 9 to be folded into the addressing mode unless the lone use 13432 // is an add. 13433 std::swap(MulAmt1, MulAmt2); 13434 13435 SDValue NewMul; 13436 if (isPowerOf2_64(MulAmt1)) 13437 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 13438 DAG.getConstant(Log2_64(MulAmt1), MVT::i8)); 13439 else 13440 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0), 13441 DAG.getConstant(MulAmt1, VT)); 13442 13443 if (isPowerOf2_64(MulAmt2)) 13444 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul, 13445 DAG.getConstant(Log2_64(MulAmt2), MVT::i8)); 13446 else 13447 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul, 13448 DAG.getConstant(MulAmt2, VT)); 13449 13450 // Do not add new nodes to DAG combiner worklist. 13451 DCI.CombineTo(N, NewMul, false); 13452 } 13453 return SDValue(); 13454 } 13455 13456 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) { 13457 SDValue N0 = N->getOperand(0); 13458 SDValue N1 = N->getOperand(1); 13459 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 13460 EVT VT = N0.getValueType(); 13461 13462 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2)) 13463 // since the result of setcc_c is all zero's or all ones. 13464 if (VT.isInteger() && !VT.isVector() && 13465 N1C && N0.getOpcode() == ISD::AND && 13466 N0.getOperand(1).getOpcode() == ISD::Constant) { 13467 SDValue N00 = N0.getOperand(0); 13468 if (N00.getOpcode() == X86ISD::SETCC_CARRY || 13469 ((N00.getOpcode() == ISD::ANY_EXTEND || 13470 N00.getOpcode() == ISD::ZERO_EXTEND) && 13471 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) { 13472 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 13473 APInt ShAmt = N1C->getAPIntValue(); 13474 Mask = Mask.shl(ShAmt); 13475 if (Mask != 0) 13476 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 13477 N00, DAG.getConstant(Mask, VT)); 13478 } 13479 } 13480 13481 13482 // Hardware support for vector shifts is sparse which makes us scalarize the 13483 // vector operations in many cases. Also, on sandybridge ADD is faster than 13484 // shl. 13485 // (shl V, 1) -> add V,V 13486 if (isSplatVector(N1.getNode())) { 13487 assert(N0.getValueType().isVector() && "Invalid vector shift type"); 13488 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0)); 13489 // We shift all of the values by one. In many cases we do not have 13490 // hardware support for this operation. This is better expressed as an ADD 13491 // of two values. 13492 if (N1C && (1 == N1C->getZExtValue())) { 13493 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0); 13494 } 13495 } 13496 13497 return SDValue(); 13498 } 13499 13500 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts 13501 /// when possible. 13502 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG, 13503 const X86Subtarget *Subtarget) { 13504 EVT VT = N->getValueType(0); 13505 if (N->getOpcode() == ISD::SHL) { 13506 SDValue V = PerformSHLCombine(N, DAG); 13507 if (V.getNode()) return V; 13508 } 13509 13510 // On X86 with SSE2 support, we can transform this to a vector shift if 13511 // all elements are shifted by the same amount. We can't do this in legalize 13512 // because the a constant vector is typically transformed to a constant pool 13513 // so we have no knowledge of the shift amount. 13514 if (!Subtarget->hasXMMInt()) 13515 return SDValue(); 13516 13517 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 && 13518 (!Subtarget->hasAVX2() || 13519 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16))) 13520 return SDValue(); 13521 13522 SDValue ShAmtOp = N->getOperand(1); 13523 EVT EltVT = VT.getVectorElementType(); 13524 DebugLoc DL = N->getDebugLoc(); 13525 SDValue BaseShAmt = SDValue(); 13526 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) { 13527 unsigned NumElts = VT.getVectorNumElements(); 13528 unsigned i = 0; 13529 for (; i != NumElts; ++i) { 13530 SDValue Arg = ShAmtOp.getOperand(i); 13531 if (Arg.getOpcode() == ISD::UNDEF) continue; 13532 BaseShAmt = Arg; 13533 break; 13534 } 13535 for (; i != NumElts; ++i) { 13536 SDValue Arg = ShAmtOp.getOperand(i); 13537 if (Arg.getOpcode() == ISD::UNDEF) continue; 13538 if (Arg != BaseShAmt) { 13539 return SDValue(); 13540 } 13541 } 13542 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE && 13543 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) { 13544 SDValue InVec = ShAmtOp.getOperand(0); 13545 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 13546 unsigned NumElts = InVec.getValueType().getVectorNumElements(); 13547 unsigned i = 0; 13548 for (; i != NumElts; ++i) { 13549 SDValue Arg = InVec.getOperand(i); 13550 if (Arg.getOpcode() == ISD::UNDEF) continue; 13551 BaseShAmt = Arg; 13552 break; 13553 } 13554 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) { 13555 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) { 13556 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex(); 13557 if (C->getZExtValue() == SplatIdx) 13558 BaseShAmt = InVec.getOperand(1); 13559 } 13560 } 13561 if (BaseShAmt.getNode() == 0) 13562 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp, 13563 DAG.getIntPtrConstant(0)); 13564 } else 13565 return SDValue(); 13566 13567 // The shift amount is an i32. 13568 if (EltVT.bitsGT(MVT::i32)) 13569 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt); 13570 else if (EltVT.bitsLT(MVT::i32)) 13571 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt); 13572 13573 // The shift amount is identical so we can do a vector shift. 13574 SDValue ValOp = N->getOperand(0); 13575 switch (N->getOpcode()) { 13576 default: 13577 llvm_unreachable("Unknown shift opcode!"); 13578 break; 13579 case ISD::SHL: 13580 if (VT == MVT::v2i64) 13581 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13582 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 13583 ValOp, BaseShAmt); 13584 if (VT == MVT::v4i32) 13585 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13586 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 13587 ValOp, BaseShAmt); 13588 if (VT == MVT::v8i16) 13589 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13590 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 13591 ValOp, BaseShAmt); 13592 if (VT == MVT::v4i64) 13593 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13594 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32), 13595 ValOp, BaseShAmt); 13596 if (VT == MVT::v8i32) 13597 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13598 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32), 13599 ValOp, BaseShAmt); 13600 if (VT == MVT::v16i16) 13601 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13602 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32), 13603 ValOp, BaseShAmt); 13604 break; 13605 case ISD::SRA: 13606 if (VT == MVT::v4i32) 13607 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13608 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32), 13609 ValOp, BaseShAmt); 13610 if (VT == MVT::v8i16) 13611 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13612 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32), 13613 ValOp, BaseShAmt); 13614 if (VT == MVT::v8i32) 13615 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13616 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32), 13617 ValOp, BaseShAmt); 13618 if (VT == MVT::v16i16) 13619 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13620 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32), 13621 ValOp, BaseShAmt); 13622 break; 13623 case ISD::SRL: 13624 if (VT == MVT::v2i64) 13625 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13626 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 13627 ValOp, BaseShAmt); 13628 if (VT == MVT::v4i32) 13629 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13630 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32), 13631 ValOp, BaseShAmt); 13632 if (VT == MVT::v8i16) 13633 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13634 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 13635 ValOp, BaseShAmt); 13636 if (VT == MVT::v4i64) 13637 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13638 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32), 13639 ValOp, BaseShAmt); 13640 if (VT == MVT::v8i32) 13641 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13642 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32), 13643 ValOp, BaseShAmt); 13644 if (VT == MVT::v16i16) 13645 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13646 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32), 13647 ValOp, BaseShAmt); 13648 break; 13649 } 13650 return SDValue(); 13651 } 13652 13653 13654 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..)) 13655 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS 13656 // and friends. Likewise for OR -> CMPNEQSS. 13657 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG, 13658 TargetLowering::DAGCombinerInfo &DCI, 13659 const X86Subtarget *Subtarget) { 13660 unsigned opcode; 13661 13662 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but 13663 // we're requiring SSE2 for both. 13664 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) { 13665 SDValue N0 = N->getOperand(0); 13666 SDValue N1 = N->getOperand(1); 13667 SDValue CMP0 = N0->getOperand(1); 13668 SDValue CMP1 = N1->getOperand(1); 13669 DebugLoc DL = N->getDebugLoc(); 13670 13671 // The SETCCs should both refer to the same CMP. 13672 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1) 13673 return SDValue(); 13674 13675 SDValue CMP00 = CMP0->getOperand(0); 13676 SDValue CMP01 = CMP0->getOperand(1); 13677 EVT VT = CMP00.getValueType(); 13678 13679 if (VT == MVT::f32 || VT == MVT::f64) { 13680 bool ExpectingFlags = false; 13681 // Check for any users that want flags: 13682 for (SDNode::use_iterator UI = N->use_begin(), 13683 UE = N->use_end(); 13684 !ExpectingFlags && UI != UE; ++UI) 13685 switch (UI->getOpcode()) { 13686 default: 13687 case ISD::BR_CC: 13688 case ISD::BRCOND: 13689 case ISD::SELECT: 13690 ExpectingFlags = true; 13691 break; 13692 case ISD::CopyToReg: 13693 case ISD::SIGN_EXTEND: 13694 case ISD::ZERO_EXTEND: 13695 case ISD::ANY_EXTEND: 13696 break; 13697 } 13698 13699 if (!ExpectingFlags) { 13700 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0); 13701 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0); 13702 13703 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) { 13704 X86::CondCode tmp = cc0; 13705 cc0 = cc1; 13706 cc1 = tmp; 13707 } 13708 13709 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) || 13710 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) { 13711 bool is64BitFP = (CMP00.getValueType() == MVT::f64); 13712 X86ISD::NodeType NTOperator = is64BitFP ? 13713 X86ISD::FSETCCsd : X86ISD::FSETCCss; 13714 // FIXME: need symbolic constants for these magic numbers. 13715 // See X86ATTInstPrinter.cpp:printSSECC(). 13716 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4; 13717 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01, 13718 DAG.getConstant(x86cc, MVT::i8)); 13719 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32, 13720 OnesOrZeroesF); 13721 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI, 13722 DAG.getConstant(1, MVT::i32)); 13723 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed); 13724 return OneBitOfTruth; 13725 } 13726 } 13727 } 13728 } 13729 return SDValue(); 13730 } 13731 13732 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector 13733 /// so it can be folded inside ANDNP. 13734 static bool CanFoldXORWithAllOnes(const SDNode *N) { 13735 EVT VT = N->getValueType(0); 13736 13737 // Match direct AllOnes for 128 and 256-bit vectors 13738 if (ISD::isBuildVectorAllOnes(N)) 13739 return true; 13740 13741 // Look through a bit convert. 13742 if (N->getOpcode() == ISD::BITCAST) 13743 N = N->getOperand(0).getNode(); 13744 13745 // Sometimes the operand may come from a insert_subvector building a 256-bit 13746 // allones vector 13747 if (VT.getSizeInBits() == 256 && 13748 N->getOpcode() == ISD::INSERT_SUBVECTOR) { 13749 SDValue V1 = N->getOperand(0); 13750 SDValue V2 = N->getOperand(1); 13751 13752 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR && 13753 V1.getOperand(0).getOpcode() == ISD::UNDEF && 13754 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) && 13755 ISD::isBuildVectorAllOnes(V2.getNode())) 13756 return true; 13757 } 13758 13759 return false; 13760 } 13761 13762 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG, 13763 TargetLowering::DAGCombinerInfo &DCI, 13764 const X86Subtarget *Subtarget) { 13765 if (DCI.isBeforeLegalizeOps()) 13766 return SDValue(); 13767 13768 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 13769 if (R.getNode()) 13770 return R; 13771 13772 EVT VT = N->getValueType(0); 13773 13774 // Create ANDN, BLSI, and BLSR instructions 13775 // BLSI is X & (-X) 13776 // BLSR is X & (X-1) 13777 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) { 13778 SDValue N0 = N->getOperand(0); 13779 SDValue N1 = N->getOperand(1); 13780 DebugLoc DL = N->getDebugLoc(); 13781 13782 // Check LHS for not 13783 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1))) 13784 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1); 13785 // Check RHS for not 13786 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1))) 13787 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0); 13788 13789 // Check LHS for neg 13790 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 && 13791 isZero(N0.getOperand(0))) 13792 return DAG.getNode(X86ISD::BLSI, DL, VT, N1); 13793 13794 // Check RHS for neg 13795 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 && 13796 isZero(N1.getOperand(0))) 13797 return DAG.getNode(X86ISD::BLSI, DL, VT, N0); 13798 13799 // Check LHS for X-1 13800 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 13801 isAllOnes(N0.getOperand(1))) 13802 return DAG.getNode(X86ISD::BLSR, DL, VT, N1); 13803 13804 // Check RHS for X-1 13805 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 13806 isAllOnes(N1.getOperand(1))) 13807 return DAG.getNode(X86ISD::BLSR, DL, VT, N0); 13808 13809 return SDValue(); 13810 } 13811 13812 // Want to form ANDNP nodes: 13813 // 1) In the hopes of then easily combining them with OR and AND nodes 13814 // to form PBLEND/PSIGN. 13815 // 2) To match ANDN packed intrinsics 13816 if (VT != MVT::v2i64 && VT != MVT::v4i64) 13817 return SDValue(); 13818 13819 SDValue N0 = N->getOperand(0); 13820 SDValue N1 = N->getOperand(1); 13821 DebugLoc DL = N->getDebugLoc(); 13822 13823 // Check LHS for vnot 13824 if (N0.getOpcode() == ISD::XOR && 13825 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) 13826 CanFoldXORWithAllOnes(N0.getOperand(1).getNode())) 13827 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1); 13828 13829 // Check RHS for vnot 13830 if (N1.getOpcode() == ISD::XOR && 13831 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) 13832 CanFoldXORWithAllOnes(N1.getOperand(1).getNode())) 13833 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0); 13834 13835 return SDValue(); 13836 } 13837 13838 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG, 13839 TargetLowering::DAGCombinerInfo &DCI, 13840 const X86Subtarget *Subtarget) { 13841 if (DCI.isBeforeLegalizeOps()) 13842 return SDValue(); 13843 13844 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 13845 if (R.getNode()) 13846 return R; 13847 13848 EVT VT = N->getValueType(0); 13849 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64) 13850 return SDValue(); 13851 13852 SDValue N0 = N->getOperand(0); 13853 SDValue N1 = N->getOperand(1); 13854 13855 // look for psign/blend 13856 if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) { 13857 if (VT == MVT::v2i64) { 13858 // Canonicalize pandn to RHS 13859 if (N0.getOpcode() == X86ISD::ANDNP) 13860 std::swap(N0, N1); 13861 // or (and (m, x), (pandn m, y)) 13862 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) { 13863 SDValue Mask = N1.getOperand(0); 13864 SDValue X = N1.getOperand(1); 13865 SDValue Y; 13866 if (N0.getOperand(0) == Mask) 13867 Y = N0.getOperand(1); 13868 if (N0.getOperand(1) == Mask) 13869 Y = N0.getOperand(0); 13870 13871 // Check to see if the mask appeared in both the AND and ANDNP and 13872 if (!Y.getNode()) 13873 return SDValue(); 13874 13875 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them. 13876 if (Mask.getOpcode() != ISD::BITCAST || 13877 X.getOpcode() != ISD::BITCAST || 13878 Y.getOpcode() != ISD::BITCAST) 13879 return SDValue(); 13880 13881 // Look through mask bitcast. 13882 Mask = Mask.getOperand(0); 13883 EVT MaskVT = Mask.getValueType(); 13884 13885 // Validate that the Mask operand is a vector sra node. The sra node 13886 // will be an intrinsic. 13887 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN) 13888 return SDValue(); 13889 13890 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but 13891 // there is no psrai.b 13892 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) { 13893 case Intrinsic::x86_sse2_psrai_w: 13894 case Intrinsic::x86_sse2_psrai_d: 13895 break; 13896 default: return SDValue(); 13897 } 13898 13899 // Check that the SRA is all signbits. 13900 SDValue SraC = Mask.getOperand(2); 13901 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue(); 13902 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits(); 13903 if ((SraAmt + 1) != EltBits) 13904 return SDValue(); 13905 13906 DebugLoc DL = N->getDebugLoc(); 13907 13908 // Now we know we at least have a plendvb with the mask val. See if 13909 // we can form a psignb/w/d. 13910 // psign = x.type == y.type == mask.type && y = sub(0, x); 13911 X = X.getOperand(0); 13912 Y = Y.getOperand(0); 13913 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X && 13914 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) && 13915 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){ 13916 unsigned Opc = 0; 13917 switch (EltBits) { 13918 case 8: Opc = X86ISD::PSIGNB; break; 13919 case 16: Opc = X86ISD::PSIGNW; break; 13920 case 32: Opc = X86ISD::PSIGND; break; 13921 default: break; 13922 } 13923 if (Opc) { 13924 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1)); 13925 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign); 13926 } 13927 } 13928 // PBLENDVB only available on SSE 4.1 13929 if (!(Subtarget->hasSSE41() || Subtarget->hasAVX())) 13930 return SDValue(); 13931 13932 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X); 13933 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y); 13934 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask); 13935 Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y); 13936 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask); 13937 } 13938 } 13939 } 13940 13941 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c) 13942 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 13943 std::swap(N0, N1); 13944 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 13945 return SDValue(); 13946 if (!N0.hasOneUse() || !N1.hasOneUse()) 13947 return SDValue(); 13948 13949 SDValue ShAmt0 = N0.getOperand(1); 13950 if (ShAmt0.getValueType() != MVT::i8) 13951 return SDValue(); 13952 SDValue ShAmt1 = N1.getOperand(1); 13953 if (ShAmt1.getValueType() != MVT::i8) 13954 return SDValue(); 13955 if (ShAmt0.getOpcode() == ISD::TRUNCATE) 13956 ShAmt0 = ShAmt0.getOperand(0); 13957 if (ShAmt1.getOpcode() == ISD::TRUNCATE) 13958 ShAmt1 = ShAmt1.getOperand(0); 13959 13960 DebugLoc DL = N->getDebugLoc(); 13961 unsigned Opc = X86ISD::SHLD; 13962 SDValue Op0 = N0.getOperand(0); 13963 SDValue Op1 = N1.getOperand(0); 13964 if (ShAmt0.getOpcode() == ISD::SUB) { 13965 Opc = X86ISD::SHRD; 13966 std::swap(Op0, Op1); 13967 std::swap(ShAmt0, ShAmt1); 13968 } 13969 13970 unsigned Bits = VT.getSizeInBits(); 13971 if (ShAmt1.getOpcode() == ISD::SUB) { 13972 SDValue Sum = ShAmt1.getOperand(0); 13973 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) { 13974 SDValue ShAmt1Op1 = ShAmt1.getOperand(1); 13975 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE) 13976 ShAmt1Op1 = ShAmt1Op1.getOperand(0); 13977 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0) 13978 return DAG.getNode(Opc, DL, VT, 13979 Op0, Op1, 13980 DAG.getNode(ISD::TRUNCATE, DL, 13981 MVT::i8, ShAmt0)); 13982 } 13983 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) { 13984 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0); 13985 if (ShAmt0C && 13986 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits) 13987 return DAG.getNode(Opc, DL, VT, 13988 N0.getOperand(0), N1.getOperand(0), 13989 DAG.getNode(ISD::TRUNCATE, DL, 13990 MVT::i8, ShAmt0)); 13991 } 13992 13993 return SDValue(); 13994 } 13995 13996 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG, 13997 TargetLowering::DAGCombinerInfo &DCI, 13998 const X86Subtarget *Subtarget) { 13999 if (DCI.isBeforeLegalizeOps()) 14000 return SDValue(); 14001 14002 EVT VT = N->getValueType(0); 14003 14004 if (VT != MVT::i32 && VT != MVT::i64) 14005 return SDValue(); 14006 14007 // Create BLSMSK instructions by finding X ^ (X-1) 14008 SDValue N0 = N->getOperand(0); 14009 SDValue N1 = N->getOperand(1); 14010 DebugLoc DL = N->getDebugLoc(); 14011 14012 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 14013 isAllOnes(N0.getOperand(1))) 14014 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1); 14015 14016 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 14017 isAllOnes(N1.getOperand(1))) 14018 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0); 14019 14020 return SDValue(); 14021 } 14022 14023 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes. 14024 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG, 14025 const X86Subtarget *Subtarget) { 14026 LoadSDNode *Ld = cast<LoadSDNode>(N); 14027 EVT RegVT = Ld->getValueType(0); 14028 EVT MemVT = Ld->getMemoryVT(); 14029 DebugLoc dl = Ld->getDebugLoc(); 14030 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14031 14032 ISD::LoadExtType Ext = Ld->getExtensionType(); 14033 14034 // If this is a vector EXT Load then attempt to optimize it using a 14035 // shuffle. We need SSE4 for the shuffles. 14036 // TODO: It is possible to support ZExt by zeroing the undef values 14037 // during the shuffle phase or after the shuffle. 14038 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) { 14039 assert(MemVT != RegVT && "Cannot extend to the same type"); 14040 assert(MemVT.isVector() && "Must load a vector from memory"); 14041 14042 unsigned NumElems = RegVT.getVectorNumElements(); 14043 unsigned RegSz = RegVT.getSizeInBits(); 14044 unsigned MemSz = MemVT.getSizeInBits(); 14045 assert(RegSz > MemSz && "Register size must be greater than the mem size"); 14046 // All sizes must be a power of two 14047 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue(); 14048 14049 // Attempt to load the original value using a single load op. 14050 // Find a scalar type which is equal to the loaded word size. 14051 MVT SclrLoadTy = MVT::i8; 14052 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 14053 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 14054 MVT Tp = (MVT::SimpleValueType)tp; 14055 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) { 14056 SclrLoadTy = Tp; 14057 break; 14058 } 14059 } 14060 14061 // Proceed if a load word is found. 14062 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue(); 14063 14064 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy, 14065 RegSz/SclrLoadTy.getSizeInBits()); 14066 14067 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), 14068 RegSz/MemVT.getScalarType().getSizeInBits()); 14069 // Can't shuffle using an illegal type. 14070 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 14071 14072 // Perform a single load. 14073 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), 14074 Ld->getBasePtr(), 14075 Ld->getPointerInfo(), Ld->isVolatile(), 14076 Ld->isNonTemporal(), Ld->isInvariant(), 14077 Ld->getAlignment()); 14078 14079 // Insert the word loaded into a vector. 14080 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 14081 LoadUnitVecVT, ScalarLoad); 14082 14083 // Bitcast the loaded value to a vector of the original element type, in 14084 // the size of the target vector type. 14085 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector); 14086 unsigned SizeRatio = RegSz/MemSz; 14087 14088 // Redistribute the loaded elements into the different locations. 14089 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14090 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i; 14091 14092 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec, 14093 DAG.getUNDEF(SlicedVec.getValueType()), 14094 ShuffleVec.data()); 14095 14096 // Bitcast to the requested type. 14097 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff); 14098 // Replace the original load with the new sequence 14099 // and return the new chain. 14100 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff); 14101 return SDValue(ScalarLoad.getNode(), 1); 14102 } 14103 14104 return SDValue(); 14105 } 14106 14107 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes. 14108 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG, 14109 const X86Subtarget *Subtarget) { 14110 StoreSDNode *St = cast<StoreSDNode>(N); 14111 EVT VT = St->getValue().getValueType(); 14112 EVT StVT = St->getMemoryVT(); 14113 DebugLoc dl = St->getDebugLoc(); 14114 SDValue StoredVal = St->getOperand(1); 14115 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14116 14117 // If we are saving a concatination of two XMM registers, perform two stores. 14118 // This is better in Sandy Bridge cause one 256-bit mem op is done via two 14119 // 128-bit ones. If in the future the cost becomes only one memory access the 14120 // first version would be better. 14121 if (VT.getSizeInBits() == 256 && 14122 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS && 14123 StoredVal.getNumOperands() == 2) { 14124 14125 SDValue Value0 = StoredVal.getOperand(0); 14126 SDValue Value1 = StoredVal.getOperand(1); 14127 14128 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy()); 14129 SDValue Ptr0 = St->getBasePtr(); 14130 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride); 14131 14132 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0, 14133 St->getPointerInfo(), St->isVolatile(), 14134 St->isNonTemporal(), St->getAlignment()); 14135 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1, 14136 St->getPointerInfo(), St->isVolatile(), 14137 St->isNonTemporal(), St->getAlignment()); 14138 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1); 14139 } 14140 14141 // Optimize trunc store (of multiple scalars) to shuffle and store. 14142 // First, pack all of the elements in one place. Next, store to memory 14143 // in fewer chunks. 14144 if (St->isTruncatingStore() && VT.isVector()) { 14145 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14146 unsigned NumElems = VT.getVectorNumElements(); 14147 assert(StVT != VT && "Cannot truncate to the same type"); 14148 unsigned FromSz = VT.getVectorElementType().getSizeInBits(); 14149 unsigned ToSz = StVT.getVectorElementType().getSizeInBits(); 14150 14151 // From, To sizes and ElemCount must be pow of two 14152 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue(); 14153 // We are going to use the original vector elt for storing. 14154 // Accumulated smaller vector elements must be a multiple of the store size. 14155 if (0 != (NumElems * FromSz) % ToSz) return SDValue(); 14156 14157 unsigned SizeRatio = FromSz / ToSz; 14158 14159 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits()); 14160 14161 // Create a type on which we perform the shuffle 14162 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), 14163 StVT.getScalarType(), NumElems*SizeRatio); 14164 14165 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 14166 14167 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue()); 14168 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14169 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio; 14170 14171 // Can't shuffle using an illegal type 14172 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 14173 14174 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec, 14175 DAG.getUNDEF(WideVec.getValueType()), 14176 ShuffleVec.data()); 14177 // At this point all of the data is stored at the bottom of the 14178 // register. We now need to save it to mem. 14179 14180 // Find the largest store unit 14181 MVT StoreType = MVT::i8; 14182 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 14183 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 14184 MVT Tp = (MVT::SimpleValueType)tp; 14185 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz) 14186 StoreType = Tp; 14187 } 14188 14189 // Bitcast the original vector into a vector of store-size units 14190 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 14191 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 14192 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 14193 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff); 14194 SmallVector<SDValue, 8> Chains; 14195 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, 14196 TLI.getPointerTy()); 14197 SDValue Ptr = St->getBasePtr(); 14198 14199 // Perform one or more big stores into memory. 14200 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) { 14201 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 14202 StoreType, ShuffWide, 14203 DAG.getIntPtrConstant(i)); 14204 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr, 14205 St->getPointerInfo(), St->isVolatile(), 14206 St->isNonTemporal(), St->getAlignment()); 14207 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14208 Chains.push_back(Ch); 14209 } 14210 14211 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 14212 Chains.size()); 14213 } 14214 14215 14216 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering 14217 // the FP state in cases where an emms may be missing. 14218 // A preferable solution to the general problem is to figure out the right 14219 // places to insert EMMS. This qualifies as a quick hack. 14220 14221 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode. 14222 if (VT.getSizeInBits() != 64) 14223 return SDValue(); 14224 14225 const Function *F = DAG.getMachineFunction().getFunction(); 14226 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat); 14227 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps 14228 && Subtarget->hasXMMInt(); 14229 if ((VT.isVector() || 14230 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) && 14231 isa<LoadSDNode>(St->getValue()) && 14232 !cast<LoadSDNode>(St->getValue())->isVolatile() && 14233 St->getChain().hasOneUse() && !St->isVolatile()) { 14234 SDNode* LdVal = St->getValue().getNode(); 14235 LoadSDNode *Ld = 0; 14236 int TokenFactorIndex = -1; 14237 SmallVector<SDValue, 8> Ops; 14238 SDNode* ChainVal = St->getChain().getNode(); 14239 // Must be a store of a load. We currently handle two cases: the load 14240 // is a direct child, and it's under an intervening TokenFactor. It is 14241 // possible to dig deeper under nested TokenFactors. 14242 if (ChainVal == LdVal) 14243 Ld = cast<LoadSDNode>(St->getChain()); 14244 else if (St->getValue().hasOneUse() && 14245 ChainVal->getOpcode() == ISD::TokenFactor) { 14246 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) { 14247 if (ChainVal->getOperand(i).getNode() == LdVal) { 14248 TokenFactorIndex = i; 14249 Ld = cast<LoadSDNode>(St->getValue()); 14250 } else 14251 Ops.push_back(ChainVal->getOperand(i)); 14252 } 14253 } 14254 14255 if (!Ld || !ISD::isNormalLoad(Ld)) 14256 return SDValue(); 14257 14258 // If this is not the MMX case, i.e. we are just turning i64 load/store 14259 // into f64 load/store, avoid the transformation if there are multiple 14260 // uses of the loaded value. 14261 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0)) 14262 return SDValue(); 14263 14264 DebugLoc LdDL = Ld->getDebugLoc(); 14265 DebugLoc StDL = N->getDebugLoc(); 14266 // If we are a 64-bit capable x86, lower to a single movq load/store pair. 14267 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store 14268 // pair instead. 14269 if (Subtarget->is64Bit() || F64IsLegal) { 14270 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64; 14271 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(), 14272 Ld->getPointerInfo(), Ld->isVolatile(), 14273 Ld->isNonTemporal(), Ld->isInvariant(), 14274 Ld->getAlignment()); 14275 SDValue NewChain = NewLd.getValue(1); 14276 if (TokenFactorIndex != -1) { 14277 Ops.push_back(NewChain); 14278 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 14279 Ops.size()); 14280 } 14281 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(), 14282 St->getPointerInfo(), 14283 St->isVolatile(), St->isNonTemporal(), 14284 St->getAlignment()); 14285 } 14286 14287 // Otherwise, lower to two pairs of 32-bit loads / stores. 14288 SDValue LoAddr = Ld->getBasePtr(); 14289 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr, 14290 DAG.getConstant(4, MVT::i32)); 14291 14292 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr, 14293 Ld->getPointerInfo(), 14294 Ld->isVolatile(), Ld->isNonTemporal(), 14295 Ld->isInvariant(), Ld->getAlignment()); 14296 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr, 14297 Ld->getPointerInfo().getWithOffset(4), 14298 Ld->isVolatile(), Ld->isNonTemporal(), 14299 Ld->isInvariant(), 14300 MinAlign(Ld->getAlignment(), 4)); 14301 14302 SDValue NewChain = LoLd.getValue(1); 14303 if (TokenFactorIndex != -1) { 14304 Ops.push_back(LoLd); 14305 Ops.push_back(HiLd); 14306 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 14307 Ops.size()); 14308 } 14309 14310 LoAddr = St->getBasePtr(); 14311 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr, 14312 DAG.getConstant(4, MVT::i32)); 14313 14314 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr, 14315 St->getPointerInfo(), 14316 St->isVolatile(), St->isNonTemporal(), 14317 St->getAlignment()); 14318 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr, 14319 St->getPointerInfo().getWithOffset(4), 14320 St->isVolatile(), 14321 St->isNonTemporal(), 14322 MinAlign(St->getAlignment(), 4)); 14323 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt); 14324 } 14325 return SDValue(); 14326 } 14327 14328 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal" 14329 /// and return the operands for the horizontal operation in LHS and RHS. A 14330 /// horizontal operation performs the binary operation on successive elements 14331 /// of its first operand, then on successive elements of its second operand, 14332 /// returning the resulting values in a vector. For example, if 14333 /// A = < float a0, float a1, float a2, float a3 > 14334 /// and 14335 /// B = < float b0, float b1, float b2, float b3 > 14336 /// then the result of doing a horizontal operation on A and B is 14337 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >. 14338 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form 14339 /// A horizontal-op B, for some already available A and B, and if so then LHS is 14340 /// set to A, RHS to B, and the routine returns 'true'. 14341 /// Note that the binary operation should have the property that if one of the 14342 /// operands is UNDEF then the result is UNDEF. 14343 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) { 14344 // Look for the following pattern: if 14345 // A = < float a0, float a1, float a2, float a3 > 14346 // B = < float b0, float b1, float b2, float b3 > 14347 // and 14348 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6> 14349 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7> 14350 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 > 14351 // which is A horizontal-op B. 14352 14353 // At least one of the operands should be a vector shuffle. 14354 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14355 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) 14356 return false; 14357 14358 EVT VT = LHS.getValueType(); 14359 unsigned N = VT.getVectorNumElements(); 14360 14361 // View LHS in the form 14362 // LHS = VECTOR_SHUFFLE A, B, LMask 14363 // If LHS is not a shuffle then pretend it is the shuffle 14364 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1> 14365 // NOTE: in what follows a default initialized SDValue represents an UNDEF of 14366 // type VT. 14367 SDValue A, B; 14368 SmallVector<int, 8> LMask(N); 14369 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 14370 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF) 14371 A = LHS.getOperand(0); 14372 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF) 14373 B = LHS.getOperand(1); 14374 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask); 14375 } else { 14376 if (LHS.getOpcode() != ISD::UNDEF) 14377 A = LHS; 14378 for (unsigned i = 0; i != N; ++i) 14379 LMask[i] = i; 14380 } 14381 14382 // Likewise, view RHS in the form 14383 // RHS = VECTOR_SHUFFLE C, D, RMask 14384 SDValue C, D; 14385 SmallVector<int, 8> RMask(N); 14386 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 14387 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF) 14388 C = RHS.getOperand(0); 14389 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF) 14390 D = RHS.getOperand(1); 14391 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask); 14392 } else { 14393 if (RHS.getOpcode() != ISD::UNDEF) 14394 C = RHS; 14395 for (unsigned i = 0; i != N; ++i) 14396 RMask[i] = i; 14397 } 14398 14399 // Check that the shuffles are both shuffling the same vectors. 14400 if (!(A == C && B == D) && !(A == D && B == C)) 14401 return false; 14402 14403 // If everything is UNDEF then bail out: it would be better to fold to UNDEF. 14404 if (!A.getNode() && !B.getNode()) 14405 return false; 14406 14407 // If A and B occur in reverse order in RHS, then "swap" them (which means 14408 // rewriting the mask). 14409 if (A != C) 14410 for (unsigned i = 0; i != N; ++i) { 14411 unsigned Idx = RMask[i]; 14412 if (Idx < N) 14413 RMask[i] += N; 14414 else if (Idx < 2*N) 14415 RMask[i] -= N; 14416 } 14417 14418 // At this point LHS and RHS are equivalent to 14419 // LHS = VECTOR_SHUFFLE A, B, LMask 14420 // RHS = VECTOR_SHUFFLE A, B, RMask 14421 // Check that the masks correspond to performing a horizontal operation. 14422 for (unsigned i = 0; i != N; ++i) { 14423 unsigned LIdx = LMask[i], RIdx = RMask[i]; 14424 14425 // Ignore any UNDEF components. 14426 if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N)) 14427 || (!B.getNode() && (LIdx >= N || RIdx >= N))) 14428 continue; 14429 14430 // Check that successive elements are being operated on. If not, this is 14431 // not a horizontal operation. 14432 if (!(LIdx == 2*i && RIdx == 2*i + 1) && 14433 !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i)) 14434 return false; 14435 } 14436 14437 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it. 14438 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it. 14439 return true; 14440 } 14441 14442 /// PerformFADDCombine - Do target-specific dag combines on floating point adds. 14443 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG, 14444 const X86Subtarget *Subtarget) { 14445 EVT VT = N->getValueType(0); 14446 SDValue LHS = N->getOperand(0); 14447 SDValue RHS = N->getOperand(1); 14448 14449 // Try to synthesize horizontal adds from adds of shuffles. 14450 if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) && 14451 (VT == MVT::v4f32 || VT == MVT::v2f64) && 14452 isHorizontalBinOp(LHS, RHS, true)) 14453 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS); 14454 return SDValue(); 14455 } 14456 14457 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs. 14458 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG, 14459 const X86Subtarget *Subtarget) { 14460 EVT VT = N->getValueType(0); 14461 SDValue LHS = N->getOperand(0); 14462 SDValue RHS = N->getOperand(1); 14463 14464 // Try to synthesize horizontal subs from subs of shuffles. 14465 if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) && 14466 (VT == MVT::v4f32 || VT == MVT::v2f64) && 14467 isHorizontalBinOp(LHS, RHS, false)) 14468 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS); 14469 return SDValue(); 14470 } 14471 14472 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and 14473 /// X86ISD::FXOR nodes. 14474 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) { 14475 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR); 14476 // F[X]OR(0.0, x) -> x 14477 // F[X]OR(x, 0.0) -> x 14478 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 14479 if (C->getValueAPF().isPosZero()) 14480 return N->getOperand(1); 14481 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 14482 if (C->getValueAPF().isPosZero()) 14483 return N->getOperand(0); 14484 return SDValue(); 14485 } 14486 14487 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes. 14488 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) { 14489 // FAND(0.0, x) -> 0.0 14490 // FAND(x, 0.0) -> 0.0 14491 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 14492 if (C->getValueAPF().isPosZero()) 14493 return N->getOperand(0); 14494 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 14495 if (C->getValueAPF().isPosZero()) 14496 return N->getOperand(1); 14497 return SDValue(); 14498 } 14499 14500 static SDValue PerformBTCombine(SDNode *N, 14501 SelectionDAG &DAG, 14502 TargetLowering::DAGCombinerInfo &DCI) { 14503 // BT ignores high bits in the bit index operand. 14504 SDValue Op1 = N->getOperand(1); 14505 if (Op1.hasOneUse()) { 14506 unsigned BitWidth = Op1.getValueSizeInBits(); 14507 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth)); 14508 APInt KnownZero, KnownOne; 14509 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 14510 !DCI.isBeforeLegalizeOps()); 14511 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14512 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) || 14513 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO)) 14514 DCI.CommitTargetLoweringOpt(TLO); 14515 } 14516 return SDValue(); 14517 } 14518 14519 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) { 14520 SDValue Op = N->getOperand(0); 14521 if (Op.getOpcode() == ISD::BITCAST) 14522 Op = Op.getOperand(0); 14523 EVT VT = N->getValueType(0), OpVT = Op.getValueType(); 14524 if (Op.getOpcode() == X86ISD::VZEXT_LOAD && 14525 VT.getVectorElementType().getSizeInBits() == 14526 OpVT.getVectorElementType().getSizeInBits()) { 14527 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op); 14528 } 14529 return SDValue(); 14530 } 14531 14532 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) { 14533 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) -> 14534 // (and (i32 x86isd::setcc_carry), 1) 14535 // This eliminates the zext. This transformation is necessary because 14536 // ISD::SETCC is always legalized to i8. 14537 DebugLoc dl = N->getDebugLoc(); 14538 SDValue N0 = N->getOperand(0); 14539 EVT VT = N->getValueType(0); 14540 if (N0.getOpcode() == ISD::AND && 14541 N0.hasOneUse() && 14542 N0.getOperand(0).hasOneUse()) { 14543 SDValue N00 = N0.getOperand(0); 14544 if (N00.getOpcode() != X86ISD::SETCC_CARRY) 14545 return SDValue(); 14546 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 14547 if (!C || C->getZExtValue() != 1) 14548 return SDValue(); 14549 return DAG.getNode(ISD::AND, dl, VT, 14550 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, 14551 N00.getOperand(0), N00.getOperand(1)), 14552 DAG.getConstant(1, VT)); 14553 } 14554 14555 return SDValue(); 14556 } 14557 14558 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT 14559 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) { 14560 unsigned X86CC = N->getConstantOperandVal(0); 14561 SDValue EFLAG = N->getOperand(1); 14562 DebugLoc DL = N->getDebugLoc(); 14563 14564 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without 14565 // a zext and produces an all-ones bit which is more useful than 0/1 in some 14566 // cases. 14567 if (X86CC == X86::COND_B) 14568 return DAG.getNode(ISD::AND, DL, MVT::i8, 14569 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8, 14570 DAG.getConstant(X86CC, MVT::i8), EFLAG), 14571 DAG.getConstant(1, MVT::i8)); 14572 14573 return SDValue(); 14574 } 14575 14576 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, 14577 const X86TargetLowering *XTLI) { 14578 SDValue Op0 = N->getOperand(0); 14579 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have 14580 // a 32-bit target where SSE doesn't support i64->FP operations. 14581 if (Op0.getOpcode() == ISD::LOAD) { 14582 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode()); 14583 EVT VT = Ld->getValueType(0); 14584 if (!Ld->isVolatile() && !N->getValueType(0).isVector() && 14585 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() && 14586 !XTLI->getSubtarget()->is64Bit() && 14587 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 14588 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0), 14589 Ld->getChain(), Op0, DAG); 14590 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1)); 14591 return FILDChain; 14592 } 14593 } 14594 return SDValue(); 14595 } 14596 14597 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS 14598 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG, 14599 X86TargetLowering::DAGCombinerInfo &DCI) { 14600 // If the LHS and RHS of the ADC node are zero, then it can't overflow and 14601 // the result is either zero or one (depending on the input carry bit). 14602 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1. 14603 if (X86::isZeroNode(N->getOperand(0)) && 14604 X86::isZeroNode(N->getOperand(1)) && 14605 // We don't have a good way to replace an EFLAGS use, so only do this when 14606 // dead right now. 14607 SDValue(N, 1).use_empty()) { 14608 DebugLoc DL = N->getDebugLoc(); 14609 EVT VT = N->getValueType(0); 14610 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1)); 14611 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT, 14612 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, 14613 DAG.getConstant(X86::COND_B,MVT::i8), 14614 N->getOperand(2)), 14615 DAG.getConstant(1, VT)); 14616 return DCI.CombineTo(N, Res1, CarryOut); 14617 } 14618 14619 return SDValue(); 14620 } 14621 14622 // fold (add Y, (sete X, 0)) -> adc 0, Y 14623 // (add Y, (setne X, 0)) -> sbb -1, Y 14624 // (sub (sete X, 0), Y) -> sbb 0, Y 14625 // (sub (setne X, 0), Y) -> adc -1, Y 14626 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) { 14627 DebugLoc DL = N->getDebugLoc(); 14628 14629 // Look through ZExts. 14630 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0); 14631 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse()) 14632 return SDValue(); 14633 14634 SDValue SetCC = Ext.getOperand(0); 14635 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse()) 14636 return SDValue(); 14637 14638 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0); 14639 if (CC != X86::COND_E && CC != X86::COND_NE) 14640 return SDValue(); 14641 14642 SDValue Cmp = SetCC.getOperand(1); 14643 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() || 14644 !X86::isZeroNode(Cmp.getOperand(1)) || 14645 !Cmp.getOperand(0).getValueType().isInteger()) 14646 return SDValue(); 14647 14648 SDValue CmpOp0 = Cmp.getOperand(0); 14649 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0, 14650 DAG.getConstant(1, CmpOp0.getValueType())); 14651 14652 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1); 14653 if (CC == X86::COND_NE) 14654 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB, 14655 DL, OtherVal.getValueType(), OtherVal, 14656 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp); 14657 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC, 14658 DL, OtherVal.getValueType(), OtherVal, 14659 DAG.getConstant(0, OtherVal.getValueType()), NewCmp); 14660 } 14661 14662 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) { 14663 SDValue Op0 = N->getOperand(0); 14664 SDValue Op1 = N->getOperand(1); 14665 14666 // X86 can't encode an immediate LHS of a sub. See if we can push the 14667 // negation into a preceding instruction. 14668 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) { 14669 // If the RHS of the sub is a XOR with one use and a constant, invert the 14670 // immediate. Then add one to the LHS of the sub so we can turn 14671 // X-Y -> X+~Y+1, saving one register. 14672 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR && 14673 isa<ConstantSDNode>(Op1.getOperand(1))) { 14674 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue(); 14675 EVT VT = Op0.getValueType(); 14676 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT, 14677 Op1.getOperand(0), 14678 DAG.getConstant(~XorC, VT)); 14679 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor, 14680 DAG.getConstant(C->getAPIntValue()+1, VT)); 14681 } 14682 } 14683 14684 return OptimizeConditionalInDecrement(N, DAG); 14685 } 14686 14687 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N, 14688 DAGCombinerInfo &DCI) const { 14689 SelectionDAG &DAG = DCI.DAG; 14690 switch (N->getOpcode()) { 14691 default: break; 14692 case ISD::EXTRACT_VECTOR_ELT: 14693 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this); 14694 case ISD::VSELECT: 14695 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget); 14696 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI); 14697 case ISD::ADD: return OptimizeConditionalInDecrement(N, DAG); 14698 case ISD::SUB: return PerformSubCombine(N, DAG); 14699 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI); 14700 case ISD::MUL: return PerformMulCombine(N, DAG, DCI); 14701 case ISD::SHL: 14702 case ISD::SRA: 14703 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget); 14704 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget); 14705 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget); 14706 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget); 14707 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget); 14708 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget); 14709 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this); 14710 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget); 14711 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget); 14712 case X86ISD::FXOR: 14713 case X86ISD::FOR: return PerformFORCombine(N, DAG); 14714 case X86ISD::FAND: return PerformFANDCombine(N, DAG); 14715 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI); 14716 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG); 14717 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG); 14718 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG); 14719 case X86ISD::SHUFPS: // Handle all target specific shuffles 14720 case X86ISD::SHUFPD: 14721 case X86ISD::PALIGN: 14722 case X86ISD::PUNPCKHBW: 14723 case X86ISD::PUNPCKHWD: 14724 case X86ISD::PUNPCKHDQ: 14725 case X86ISD::PUNPCKHQDQ: 14726 case X86ISD::UNPCKHPS: 14727 case X86ISD::UNPCKHPD: 14728 case X86ISD::VUNPCKHPSY: 14729 case X86ISD::VUNPCKHPDY: 14730 case X86ISD::PUNPCKLBW: 14731 case X86ISD::PUNPCKLWD: 14732 case X86ISD::PUNPCKLDQ: 14733 case X86ISD::PUNPCKLQDQ: 14734 case X86ISD::UNPCKLPS: 14735 case X86ISD::UNPCKLPD: 14736 case X86ISD::VUNPCKLPSY: 14737 case X86ISD::VUNPCKLPDY: 14738 case X86ISD::MOVHLPS: 14739 case X86ISD::MOVLHPS: 14740 case X86ISD::PSHUFD: 14741 case X86ISD::PSHUFHW: 14742 case X86ISD::PSHUFLW: 14743 case X86ISD::MOVSS: 14744 case X86ISD::MOVSD: 14745 case X86ISD::VPERMILPS: 14746 case X86ISD::VPERMILPSY: 14747 case X86ISD::VPERMILPD: 14748 case X86ISD::VPERMILPDY: 14749 case X86ISD::VPERM2F128: 14750 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget); 14751 } 14752 14753 return SDValue(); 14754 } 14755 14756 /// isTypeDesirableForOp - Return true if the target has native support for 14757 /// the specified value type and it is 'desirable' to use the type for the 14758 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16 14759 /// instruction encodings are longer and some i16 instructions are slow. 14760 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const { 14761 if (!isTypeLegal(VT)) 14762 return false; 14763 if (VT != MVT::i16) 14764 return true; 14765 14766 switch (Opc) { 14767 default: 14768 return true; 14769 case ISD::LOAD: 14770 case ISD::SIGN_EXTEND: 14771 case ISD::ZERO_EXTEND: 14772 case ISD::ANY_EXTEND: 14773 case ISD::SHL: 14774 case ISD::SRL: 14775 case ISD::SUB: 14776 case ISD::ADD: 14777 case ISD::MUL: 14778 case ISD::AND: 14779 case ISD::OR: 14780 case ISD::XOR: 14781 return false; 14782 } 14783 } 14784 14785 /// IsDesirableToPromoteOp - This method query the target whether it is 14786 /// beneficial for dag combiner to promote the specified node. If true, it 14787 /// should return the desired promotion type by reference. 14788 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 14789 EVT VT = Op.getValueType(); 14790 if (VT != MVT::i16) 14791 return false; 14792 14793 bool Promote = false; 14794 bool Commute = false; 14795 switch (Op.getOpcode()) { 14796 default: break; 14797 case ISD::LOAD: { 14798 LoadSDNode *LD = cast<LoadSDNode>(Op); 14799 // If the non-extending load has a single use and it's not live out, then it 14800 // might be folded. 14801 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&& 14802 Op.hasOneUse()*/) { 14803 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 14804 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 14805 // The only case where we'd want to promote LOAD (rather then it being 14806 // promoted as an operand is when it's only use is liveout. 14807 if (UI->getOpcode() != ISD::CopyToReg) 14808 return false; 14809 } 14810 } 14811 Promote = true; 14812 break; 14813 } 14814 case ISD::SIGN_EXTEND: 14815 case ISD::ZERO_EXTEND: 14816 case ISD::ANY_EXTEND: 14817 Promote = true; 14818 break; 14819 case ISD::SHL: 14820 case ISD::SRL: { 14821 SDValue N0 = Op.getOperand(0); 14822 // Look out for (store (shl (load), x)). 14823 if (MayFoldLoad(N0) && MayFoldIntoStore(Op)) 14824 return false; 14825 Promote = true; 14826 break; 14827 } 14828 case ISD::ADD: 14829 case ISD::MUL: 14830 case ISD::AND: 14831 case ISD::OR: 14832 case ISD::XOR: 14833 Commute = true; 14834 // fallthrough 14835 case ISD::SUB: { 14836 SDValue N0 = Op.getOperand(0); 14837 SDValue N1 = Op.getOperand(1); 14838 if (!Commute && MayFoldLoad(N1)) 14839 return false; 14840 // Avoid disabling potential load folding opportunities. 14841 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op))) 14842 return false; 14843 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op))) 14844 return false; 14845 Promote = true; 14846 } 14847 } 14848 14849 PVT = MVT::i32; 14850 return Promote; 14851 } 14852 14853 //===----------------------------------------------------------------------===// 14854 // X86 Inline Assembly Support 14855 //===----------------------------------------------------------------------===// 14856 14857 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const { 14858 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 14859 14860 std::string AsmStr = IA->getAsmString(); 14861 14862 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a" 14863 SmallVector<StringRef, 4> AsmPieces; 14864 SplitString(AsmStr, AsmPieces, ";\n"); 14865 14866 switch (AsmPieces.size()) { 14867 default: return false; 14868 case 1: 14869 AsmStr = AsmPieces[0]; 14870 AsmPieces.clear(); 14871 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace. 14872 14873 // FIXME: this should verify that we are targeting a 486 or better. If not, 14874 // we will turn this bswap into something that will be lowered to logical ops 14875 // instead of emitting the bswap asm. For now, we don't support 486 or lower 14876 // so don't worry about this. 14877 // bswap $0 14878 if (AsmPieces.size() == 2 && 14879 (AsmPieces[0] == "bswap" || 14880 AsmPieces[0] == "bswapq" || 14881 AsmPieces[0] == "bswapl") && 14882 (AsmPieces[1] == "$0" || 14883 AsmPieces[1] == "${0:q}")) { 14884 // No need to check constraints, nothing other than the equivalent of 14885 // "=r,0" would be valid here. 14886 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14887 if (!Ty || Ty->getBitWidth() % 16 != 0) 14888 return false; 14889 return IntrinsicLowering::LowerToByteSwap(CI); 14890 } 14891 // rorw $$8, ${0:w} --> llvm.bswap.i16 14892 if (CI->getType()->isIntegerTy(16) && 14893 AsmPieces.size() == 3 && 14894 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") && 14895 AsmPieces[1] == "$$8," && 14896 AsmPieces[2] == "${0:w}" && 14897 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 14898 AsmPieces.clear(); 14899 const std::string &ConstraintsStr = IA->getConstraintString(); 14900 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 14901 std::sort(AsmPieces.begin(), AsmPieces.end()); 14902 if (AsmPieces.size() == 4 && 14903 AsmPieces[0] == "~{cc}" && 14904 AsmPieces[1] == "~{dirflag}" && 14905 AsmPieces[2] == "~{flags}" && 14906 AsmPieces[3] == "~{fpsr}") { 14907 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14908 if (!Ty || Ty->getBitWidth() % 16 != 0) 14909 return false; 14910 return IntrinsicLowering::LowerToByteSwap(CI); 14911 } 14912 } 14913 break; 14914 case 3: 14915 if (CI->getType()->isIntegerTy(32) && 14916 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 14917 SmallVector<StringRef, 4> Words; 14918 SplitString(AsmPieces[0], Words, " \t,"); 14919 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 14920 Words[2] == "${0:w}") { 14921 Words.clear(); 14922 SplitString(AsmPieces[1], Words, " \t,"); 14923 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" && 14924 Words[2] == "$0") { 14925 Words.clear(); 14926 SplitString(AsmPieces[2], Words, " \t,"); 14927 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 14928 Words[2] == "${0:w}") { 14929 AsmPieces.clear(); 14930 const std::string &ConstraintsStr = IA->getConstraintString(); 14931 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 14932 std::sort(AsmPieces.begin(), AsmPieces.end()); 14933 if (AsmPieces.size() == 4 && 14934 AsmPieces[0] == "~{cc}" && 14935 AsmPieces[1] == "~{dirflag}" && 14936 AsmPieces[2] == "~{flags}" && 14937 AsmPieces[3] == "~{fpsr}") { 14938 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14939 if (!Ty || Ty->getBitWidth() % 16 != 0) 14940 return false; 14941 return IntrinsicLowering::LowerToByteSwap(CI); 14942 } 14943 } 14944 } 14945 } 14946 } 14947 14948 if (CI->getType()->isIntegerTy(64)) { 14949 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 14950 if (Constraints.size() >= 2 && 14951 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" && 14952 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") { 14953 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64 14954 SmallVector<StringRef, 4> Words; 14955 SplitString(AsmPieces[0], Words, " \t"); 14956 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") { 14957 Words.clear(); 14958 SplitString(AsmPieces[1], Words, " \t"); 14959 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") { 14960 Words.clear(); 14961 SplitString(AsmPieces[2], Words, " \t,"); 14962 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" && 14963 Words[2] == "%edx") { 14964 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14965 if (!Ty || Ty->getBitWidth() % 16 != 0) 14966 return false; 14967 return IntrinsicLowering::LowerToByteSwap(CI); 14968 } 14969 } 14970 } 14971 } 14972 } 14973 break; 14974 } 14975 return false; 14976 } 14977 14978 14979 14980 /// getConstraintType - Given a constraint letter, return the type of 14981 /// constraint it is for this target. 14982 X86TargetLowering::ConstraintType 14983 X86TargetLowering::getConstraintType(const std::string &Constraint) const { 14984 if (Constraint.size() == 1) { 14985 switch (Constraint[0]) { 14986 case 'R': 14987 case 'q': 14988 case 'Q': 14989 case 'f': 14990 case 't': 14991 case 'u': 14992 case 'y': 14993 case 'x': 14994 case 'Y': 14995 case 'l': 14996 return C_RegisterClass; 14997 case 'a': 14998 case 'b': 14999 case 'c': 15000 case 'd': 15001 case 'S': 15002 case 'D': 15003 case 'A': 15004 return C_Register; 15005 case 'I': 15006 case 'J': 15007 case 'K': 15008 case 'L': 15009 case 'M': 15010 case 'N': 15011 case 'G': 15012 case 'C': 15013 case 'e': 15014 case 'Z': 15015 return C_Other; 15016 default: 15017 break; 15018 } 15019 } 15020 return TargetLowering::getConstraintType(Constraint); 15021 } 15022 15023 /// Examine constraint type and operand type and determine a weight value. 15024 /// This object must already have been set up with the operand type 15025 /// and the current alternative constraint selected. 15026 TargetLowering::ConstraintWeight 15027 X86TargetLowering::getSingleConstraintMatchWeight( 15028 AsmOperandInfo &info, const char *constraint) const { 15029 ConstraintWeight weight = CW_Invalid; 15030 Value *CallOperandVal = info.CallOperandVal; 15031 // If we don't have a value, we can't do a match, 15032 // but allow it at the lowest weight. 15033 if (CallOperandVal == NULL) 15034 return CW_Default; 15035 Type *type = CallOperandVal->getType(); 15036 // Look at the constraint type. 15037 switch (*constraint) { 15038 default: 15039 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15040 case 'R': 15041 case 'q': 15042 case 'Q': 15043 case 'a': 15044 case 'b': 15045 case 'c': 15046 case 'd': 15047 case 'S': 15048 case 'D': 15049 case 'A': 15050 if (CallOperandVal->getType()->isIntegerTy()) 15051 weight = CW_SpecificReg; 15052 break; 15053 case 'f': 15054 case 't': 15055 case 'u': 15056 if (type->isFloatingPointTy()) 15057 weight = CW_SpecificReg; 15058 break; 15059 case 'y': 15060 if (type->isX86_MMXTy() && Subtarget->hasMMX()) 15061 weight = CW_SpecificReg; 15062 break; 15063 case 'x': 15064 case 'Y': 15065 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM()) 15066 weight = CW_Register; 15067 break; 15068 case 'I': 15069 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) { 15070 if (C->getZExtValue() <= 31) 15071 weight = CW_Constant; 15072 } 15073 break; 15074 case 'J': 15075 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15076 if (C->getZExtValue() <= 63) 15077 weight = CW_Constant; 15078 } 15079 break; 15080 case 'K': 15081 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15082 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f)) 15083 weight = CW_Constant; 15084 } 15085 break; 15086 case 'L': 15087 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15088 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff)) 15089 weight = CW_Constant; 15090 } 15091 break; 15092 case 'M': 15093 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15094 if (C->getZExtValue() <= 3) 15095 weight = CW_Constant; 15096 } 15097 break; 15098 case 'N': 15099 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15100 if (C->getZExtValue() <= 0xff) 15101 weight = CW_Constant; 15102 } 15103 break; 15104 case 'G': 15105 case 'C': 15106 if (dyn_cast<ConstantFP>(CallOperandVal)) { 15107 weight = CW_Constant; 15108 } 15109 break; 15110 case 'e': 15111 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15112 if ((C->getSExtValue() >= -0x80000000LL) && 15113 (C->getSExtValue() <= 0x7fffffffLL)) 15114 weight = CW_Constant; 15115 } 15116 break; 15117 case 'Z': 15118 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15119 if (C->getZExtValue() <= 0xffffffff) 15120 weight = CW_Constant; 15121 } 15122 break; 15123 } 15124 return weight; 15125 } 15126 15127 /// LowerXConstraint - try to replace an X constraint, which matches anything, 15128 /// with another that has more specific requirements based on the type of the 15129 /// corresponding operand. 15130 const char *X86TargetLowering:: 15131 LowerXConstraint(EVT ConstraintVT) const { 15132 // FP X constraints get lowered to SSE1/2 registers if available, otherwise 15133 // 'f' like normal targets. 15134 if (ConstraintVT.isFloatingPoint()) { 15135 if (Subtarget->hasXMMInt()) 15136 return "Y"; 15137 if (Subtarget->hasXMM()) 15138 return "x"; 15139 } 15140 15141 return TargetLowering::LowerXConstraint(ConstraintVT); 15142 } 15143 15144 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15145 /// vector. If it is invalid, don't add anything to Ops. 15146 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15147 std::string &Constraint, 15148 std::vector<SDValue>&Ops, 15149 SelectionDAG &DAG) const { 15150 SDValue Result(0, 0); 15151 15152 // Only support length 1 constraints for now. 15153 if (Constraint.length() > 1) return; 15154 15155 char ConstraintLetter = Constraint[0]; 15156 switch (ConstraintLetter) { 15157 default: break; 15158 case 'I': 15159 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15160 if (C->getZExtValue() <= 31) { 15161 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 15162 break; 15163 } 15164 } 15165 return; 15166 case 'J': 15167 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15168 if (C->getZExtValue() <= 63) { 15169 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 15170 break; 15171 } 15172 } 15173 return; 15174 case 'K': 15175 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15176 if ((int8_t)C->getSExtValue() == C->getSExtValue()) { 15177 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 15178 break; 15179 } 15180 } 15181 return; 15182 case 'N': 15183 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15184 if (C->getZExtValue() <= 255) { 15185 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 15186 break; 15187 } 15188 } 15189 return; 15190 case 'e': { 15191 // 32-bit signed value 15192 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15193 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 15194 C->getSExtValue())) { 15195 // Widen to 64 bits here to get it sign extended. 15196 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64); 15197 break; 15198 } 15199 // FIXME gcc accepts some relocatable values here too, but only in certain 15200 // memory models; it's complicated. 15201 } 15202 return; 15203 } 15204 case 'Z': { 15205 // 32-bit unsigned value 15206 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15207 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 15208 C->getZExtValue())) { 15209 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 15210 break; 15211 } 15212 } 15213 // FIXME gcc accepts some relocatable values here too, but only in certain 15214 // memory models; it's complicated. 15215 return; 15216 } 15217 case 'i': { 15218 // Literal immediates are always ok. 15219 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) { 15220 // Widen to 64 bits here to get it sign extended. 15221 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64); 15222 break; 15223 } 15224 15225 // In any sort of PIC mode addresses need to be computed at runtime by 15226 // adding in a register or some sort of table lookup. These can't 15227 // be used as immediates. 15228 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC()) 15229 return; 15230 15231 // If we are in non-pic codegen mode, we allow the address of a global (with 15232 // an optional displacement) to be used with 'i'. 15233 GlobalAddressSDNode *GA = 0; 15234 int64_t Offset = 0; 15235 15236 // Match either (GA), (GA+C), (GA+C1+C2), etc. 15237 while (1) { 15238 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) { 15239 Offset += GA->getOffset(); 15240 break; 15241 } else if (Op.getOpcode() == ISD::ADD) { 15242 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 15243 Offset += C->getZExtValue(); 15244 Op = Op.getOperand(0); 15245 continue; 15246 } 15247 } else if (Op.getOpcode() == ISD::SUB) { 15248 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 15249 Offset += -C->getZExtValue(); 15250 Op = Op.getOperand(0); 15251 continue; 15252 } 15253 } 15254 15255 // Otherwise, this isn't something we can handle, reject it. 15256 return; 15257 } 15258 15259 const GlobalValue *GV = GA->getGlobal(); 15260 // If we require an extra load to get this address, as in PIC mode, we 15261 // can't accept it. 15262 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV, 15263 getTargetMachine()))) 15264 return; 15265 15266 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), 15267 GA->getValueType(0), Offset); 15268 break; 15269 } 15270 } 15271 15272 if (Result.getNode()) { 15273 Ops.push_back(Result); 15274 return; 15275 } 15276 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15277 } 15278 15279 std::pair<unsigned, const TargetRegisterClass*> 15280 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 15281 EVT VT) const { 15282 // First, see if this is a constraint that directly corresponds to an LLVM 15283 // register class. 15284 if (Constraint.size() == 1) { 15285 // GCC Constraint Letters 15286 switch (Constraint[0]) { 15287 default: break; 15288 // TODO: Slight differences here in allocation order and leaving 15289 // RIP in the class. Do they matter any more here than they do 15290 // in the normal allocation? 15291 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode. 15292 if (Subtarget->is64Bit()) { 15293 if (VT == MVT::i32 || VT == MVT::f32) 15294 return std::make_pair(0U, X86::GR32RegisterClass); 15295 else if (VT == MVT::i16) 15296 return std::make_pair(0U, X86::GR16RegisterClass); 15297 else if (VT == MVT::i8 || VT == MVT::i1) 15298 return std::make_pair(0U, X86::GR8RegisterClass); 15299 else if (VT == MVT::i64 || VT == MVT::f64) 15300 return std::make_pair(0U, X86::GR64RegisterClass); 15301 break; 15302 } 15303 // 32-bit fallthrough 15304 case 'Q': // Q_REGS 15305 if (VT == MVT::i32 || VT == MVT::f32) 15306 return std::make_pair(0U, X86::GR32_ABCDRegisterClass); 15307 else if (VT == MVT::i16) 15308 return std::make_pair(0U, X86::GR16_ABCDRegisterClass); 15309 else if (VT == MVT::i8 || VT == MVT::i1) 15310 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass); 15311 else if (VT == MVT::i64) 15312 return std::make_pair(0U, X86::GR64_ABCDRegisterClass); 15313 break; 15314 case 'r': // GENERAL_REGS 15315 case 'l': // INDEX_REGS 15316 if (VT == MVT::i8 || VT == MVT::i1) 15317 return std::make_pair(0U, X86::GR8RegisterClass); 15318 if (VT == MVT::i16) 15319 return std::make_pair(0U, X86::GR16RegisterClass); 15320 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit()) 15321 return std::make_pair(0U, X86::GR32RegisterClass); 15322 return std::make_pair(0U, X86::GR64RegisterClass); 15323 case 'R': // LEGACY_REGS 15324 if (VT == MVT::i8 || VT == MVT::i1) 15325 return std::make_pair(0U, X86::GR8_NOREXRegisterClass); 15326 if (VT == MVT::i16) 15327 return std::make_pair(0U, X86::GR16_NOREXRegisterClass); 15328 if (VT == MVT::i32 || !Subtarget->is64Bit()) 15329 return std::make_pair(0U, X86::GR32_NOREXRegisterClass); 15330 return std::make_pair(0U, X86::GR64_NOREXRegisterClass); 15331 case 'f': // FP Stack registers. 15332 // If SSE is enabled for this VT, use f80 to ensure the isel moves the 15333 // value to the correct fpstack register class. 15334 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT)) 15335 return std::make_pair(0U, X86::RFP32RegisterClass); 15336 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT)) 15337 return std::make_pair(0U, X86::RFP64RegisterClass); 15338 return std::make_pair(0U, X86::RFP80RegisterClass); 15339 case 'y': // MMX_REGS if MMX allowed. 15340 if (!Subtarget->hasMMX()) break; 15341 return std::make_pair(0U, X86::VR64RegisterClass); 15342 case 'Y': // SSE_REGS if SSE2 allowed 15343 if (!Subtarget->hasXMMInt()) break; 15344 // FALL THROUGH. 15345 case 'x': // SSE_REGS if SSE1 allowed 15346 if (!Subtarget->hasXMM()) break; 15347 15348 switch (VT.getSimpleVT().SimpleTy) { 15349 default: break; 15350 // Scalar SSE types. 15351 case MVT::f32: 15352 case MVT::i32: 15353 return std::make_pair(0U, X86::FR32RegisterClass); 15354 case MVT::f64: 15355 case MVT::i64: 15356 return std::make_pair(0U, X86::FR64RegisterClass); 15357 // Vector types. 15358 case MVT::v16i8: 15359 case MVT::v8i16: 15360 case MVT::v4i32: 15361 case MVT::v2i64: 15362 case MVT::v4f32: 15363 case MVT::v2f64: 15364 return std::make_pair(0U, X86::VR128RegisterClass); 15365 } 15366 break; 15367 } 15368 } 15369 15370 // Use the default implementation in TargetLowering to convert the register 15371 // constraint into a member of a register class. 15372 std::pair<unsigned, const TargetRegisterClass*> Res; 15373 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 15374 15375 // Not found as a standard register? 15376 if (Res.second == 0) { 15377 // Map st(0) -> st(7) -> ST0 15378 if (Constraint.size() == 7 && Constraint[0] == '{' && 15379 tolower(Constraint[1]) == 's' && 15380 tolower(Constraint[2]) == 't' && 15381 Constraint[3] == '(' && 15382 (Constraint[4] >= '0' && Constraint[4] <= '7') && 15383 Constraint[5] == ')' && 15384 Constraint[6] == '}') { 15385 15386 Res.first = X86::ST0+Constraint[4]-'0'; 15387 Res.second = X86::RFP80RegisterClass; 15388 return Res; 15389 } 15390 15391 // GCC allows "st(0)" to be called just plain "st". 15392 if (StringRef("{st}").equals_lower(Constraint)) { 15393 Res.first = X86::ST0; 15394 Res.second = X86::RFP80RegisterClass; 15395 return Res; 15396 } 15397 15398 // flags -> EFLAGS 15399 if (StringRef("{flags}").equals_lower(Constraint)) { 15400 Res.first = X86::EFLAGS; 15401 Res.second = X86::CCRRegisterClass; 15402 return Res; 15403 } 15404 15405 // 'A' means EAX + EDX. 15406 if (Constraint == "A") { 15407 Res.first = X86::EAX; 15408 Res.second = X86::GR32_ADRegisterClass; 15409 return Res; 15410 } 15411 return Res; 15412 } 15413 15414 // Otherwise, check to see if this is a register class of the wrong value 15415 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to 15416 // turn into {ax},{dx}. 15417 if (Res.second->hasType(VT)) 15418 return Res; // Correct type already, nothing to do. 15419 15420 // All of the single-register GCC register classes map their values onto 15421 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we 15422 // really want an 8-bit or 32-bit register, map to the appropriate register 15423 // class and return the appropriate register. 15424 if (Res.second == X86::GR16RegisterClass) { 15425 if (VT == MVT::i8) { 15426 unsigned DestReg = 0; 15427 switch (Res.first) { 15428 default: break; 15429 case X86::AX: DestReg = X86::AL; break; 15430 case X86::DX: DestReg = X86::DL; break; 15431 case X86::CX: DestReg = X86::CL; break; 15432 case X86::BX: DestReg = X86::BL; break; 15433 } 15434 if (DestReg) { 15435 Res.first = DestReg; 15436 Res.second = X86::GR8RegisterClass; 15437 } 15438 } else if (VT == MVT::i32) { 15439 unsigned DestReg = 0; 15440 switch (Res.first) { 15441 default: break; 15442 case X86::AX: DestReg = X86::EAX; break; 15443 case X86::DX: DestReg = X86::EDX; break; 15444 case X86::CX: DestReg = X86::ECX; break; 15445 case X86::BX: DestReg = X86::EBX; break; 15446 case X86::SI: DestReg = X86::ESI; break; 15447 case X86::DI: DestReg = X86::EDI; break; 15448 case X86::BP: DestReg = X86::EBP; break; 15449 case X86::SP: DestReg = X86::ESP; break; 15450 } 15451 if (DestReg) { 15452 Res.first = DestReg; 15453 Res.second = X86::GR32RegisterClass; 15454 } 15455 } else if (VT == MVT::i64) { 15456 unsigned DestReg = 0; 15457 switch (Res.first) { 15458 default: break; 15459 case X86::AX: DestReg = X86::RAX; break; 15460 case X86::DX: DestReg = X86::RDX; break; 15461 case X86::CX: DestReg = X86::RCX; break; 15462 case X86::BX: DestReg = X86::RBX; break; 15463 case X86::SI: DestReg = X86::RSI; break; 15464 case X86::DI: DestReg = X86::RDI; break; 15465 case X86::BP: DestReg = X86::RBP; break; 15466 case X86::SP: DestReg = X86::RSP; break; 15467 } 15468 if (DestReg) { 15469 Res.first = DestReg; 15470 Res.second = X86::GR64RegisterClass; 15471 } 15472 } 15473 } else if (Res.second == X86::FR32RegisterClass || 15474 Res.second == X86::FR64RegisterClass || 15475 Res.second == X86::VR128RegisterClass) { 15476 // Handle references to XMM physical registers that got mapped into the 15477 // wrong class. This can happen with constraints like {xmm0} where the 15478 // target independent register mapper will just pick the first match it can 15479 // find, ignoring the required type. 15480 if (VT == MVT::f32) 15481 Res.second = X86::FR32RegisterClass; 15482 else if (VT == MVT::f64) 15483 Res.second = X86::FR64RegisterClass; 15484 else if (X86::VR128RegisterClass->hasType(VT)) 15485 Res.second = X86::VR128RegisterClass; 15486 } 15487 15488 return Res; 15489 } 15490