X86ISelLowering.cpp revision c4db4e5105ccd82df19f141957511f735a9be2d0
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/CodeGen/PseudoSourceValue.h" 39#include "llvm/MC/MCAsmInfo.h" 40#include "llvm/MC/MCContext.h" 41#include "llvm/MC/MCExpr.h" 42#include "llvm/MC/MCSymbol.h" 43#include "llvm/ADT/BitVector.h" 44#include "llvm/ADT/SmallSet.h" 45#include "llvm/ADT/Statistic.h" 46#include "llvm/ADT/StringExtras.h" 47#include "llvm/ADT/VectorExtras.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" 53using namespace llvm; 54using namespace dwarf; 55 56STATISTIC(NumTailCalls, "Number of tail calls"); 57 58// Forward declarations. 59static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 60 SDValue V2); 61 62static SDValue Insert128BitVector(SDValue Result, 63 SDValue Vec, 64 SDValue Idx, 65 SelectionDAG &DAG, 66 DebugLoc dl); 67 68static SDValue Extract128BitVector(SDValue Vec, 69 SDValue Idx, 70 SelectionDAG &DAG, 71 DebugLoc dl); 72 73static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG); 74 75 76/// Generate a DAG to grab 128-bits from a vector > 128 bits. This 77/// sets things up to match to an AVX VEXTRACTF128 instruction or a 78/// simple subregister reference. Idx is an index in the 128 bits we 79/// want. It need not be aligned to a 128-bit bounday. That makes 80/// lowering EXTRACT_VECTOR_ELT operations easier. 81static SDValue Extract128BitVector(SDValue Vec, 82 SDValue Idx, 83 SelectionDAG &DAG, 84 DebugLoc dl) { 85 EVT VT = Vec.getValueType(); 86 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!"); 87 88 EVT ElVT = VT.getVectorElementType(); 89 90 int Factor = VT.getSizeInBits() / 128; 91 92 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), 93 ElVT, 94 VT.getVectorNumElements() / Factor); 95 96 // Extract from UNDEF is UNDEF. 97 if (Vec.getOpcode() == ISD::UNDEF) 98 return DAG.getNode(ISD::UNDEF, dl, ResultVT); 99 100 if (isa<ConstantSDNode>(Idx)) { 101 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 102 103 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR 104 // we can match to VEXTRACTF128. 105 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 106 107 // This is the index of the first element of the 128-bit chunk 108 // we want. 109 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 110 * ElemsPerChunk); 111 112 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 113 114 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, 115 VecIdx); 116 117 return Result; 118 } 119 120 return SDValue(); 121} 122 123/// Generate a DAG to put 128-bits into a vector > 128 bits. This 124/// sets things up to match to an AVX VINSERTF128 instruction or a 125/// simple superregister reference. Idx is an index in the 128 bits 126/// we want. It need not be aligned to a 128-bit bounday. That makes 127/// lowering INSERT_VECTOR_ELT operations easier. 128static SDValue Insert128BitVector(SDValue Result, 129 SDValue Vec, 130 SDValue Idx, 131 SelectionDAG &DAG, 132 DebugLoc dl) { 133 if (isa<ConstantSDNode>(Idx)) { 134 EVT VT = Vec.getValueType(); 135 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!"); 136 137 EVT ElVT = VT.getVectorElementType(); 138 139 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 140 141 EVT ResultVT = Result.getValueType(); 142 143 // Insert the relevant 128 bits. 144 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 145 146 // This is the index of the first element of the 128-bit chunk 147 // we want. 148 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 149 * ElemsPerChunk); 150 151 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 152 153 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, 154 VecIdx); 155 return Result; 156 } 157 158 return SDValue(); 159} 160 161/// Given two vectors, concat them. 162static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) { 163 DebugLoc dl = Lower.getDebugLoc(); 164 165 assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!"); 166 167 EVT VT = EVT::getVectorVT(*DAG.getContext(), 168 Lower.getValueType().getVectorElementType(), 169 Lower.getValueType().getVectorNumElements() * 2); 170 171 // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors). 172 assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!"); 173 174 // Insert the upper subvector. 175 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper, 176 DAG.getConstant( 177 // This is half the length of the result 178 // vector. Start inserting the upper 128 179 // bits here. 180 Lower.getValueType().getVectorNumElements(), 181 MVT::i32), 182 DAG, dl); 183 184 // Insert the lower subvector. 185 Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl); 186 return Vec; 187} 188 189static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) { 190 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); 191 bool is64Bit = Subtarget->is64Bit(); 192 193 if (Subtarget->isTargetEnvMacho()) { 194 if (is64Bit) 195 return new X8664_MachoTargetObjectFile(); 196 return new TargetLoweringObjectFileMachO(); 197 } 198 199 if (Subtarget->isTargetELF()) { 200 if (is64Bit) 201 return new X8664_ELFTargetObjectFile(TM); 202 return new X8632_ELFTargetObjectFile(TM); 203 } 204 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 205 return new TargetLoweringObjectFileCOFF(); 206 llvm_unreachable("unknown subtarget type"); 207} 208 209X86TargetLowering::X86TargetLowering(X86TargetMachine &TM) 210 : TargetLowering(TM, createTLOF(TM)) { 211 Subtarget = &TM.getSubtarget<X86Subtarget>(); 212 X86ScalarSSEf64 = Subtarget->hasXMMInt(); 213 X86ScalarSSEf32 = Subtarget->hasXMM(); 214 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP; 215 216 RegInfo = TM.getRegisterInfo(); 217 TD = getTargetData(); 218 219 // Set up the TargetLowering object. 220 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }; 221 222 // X86 is weird, it always uses i8 for shift amounts and setcc results. 223 setBooleanContents(ZeroOrOneBooleanContent); 224 setSchedulingPreference(Sched::RegPressure); 225 setStackPointerRegisterToSaveRestore(X86StackPtr); 226 227 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) { 228 // Setup Windows compiler runtime calls. 229 setLibcallName(RTLIB::SDIV_I64, "_alldiv"); 230 setLibcallName(RTLIB::UDIV_I64, "_aulldiv"); 231 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2"); 232 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2"); 233 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall); 234 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall); 235 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C); 236 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C); 237 } 238 239 if (Subtarget->isTargetDarwin()) { 240 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp. 241 setUseUnderscoreSetJmp(false); 242 setUseUnderscoreLongJmp(false); 243 } else if (Subtarget->isTargetMingw()) { 244 // MS runtime is weird: it exports _setjmp, but longjmp! 245 setUseUnderscoreSetJmp(true); 246 setUseUnderscoreLongJmp(false); 247 } else { 248 setUseUnderscoreSetJmp(true); 249 setUseUnderscoreLongJmp(true); 250 } 251 252 // Set up the register classes. 253 addRegisterClass(MVT::i8, X86::GR8RegisterClass); 254 addRegisterClass(MVT::i16, X86::GR16RegisterClass); 255 addRegisterClass(MVT::i32, X86::GR32RegisterClass); 256 if (Subtarget->is64Bit()) 257 addRegisterClass(MVT::i64, X86::GR64RegisterClass); 258 259 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 260 261 // We don't accept any truncstore of integer registers. 262 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 263 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 264 setTruncStoreAction(MVT::i64, MVT::i8 , Expand); 265 setTruncStoreAction(MVT::i32, MVT::i16, Expand); 266 setTruncStoreAction(MVT::i32, MVT::i8 , Expand); 267 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 268 269 // SETOEQ and SETUNE require checking two conditions. 270 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand); 271 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand); 272 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand); 273 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand); 274 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand); 275 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand); 276 277 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this 278 // operation. 279 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote); 280 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote); 281 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote); 282 283 if (Subtarget->is64Bit()) { 284 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote); 285 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand); 286 } else if (!UseSoftFloat) { 287 // We have an algorithm for SSE2->double, and we turn this into a 288 // 64-bit FILD followed by conditional FADD for other targets. 289 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 290 // We have an algorithm for SSE2, and we turn this into a 64-bit 291 // FILD for other targets. 292 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom); 293 } 294 295 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have 296 // this operation. 297 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote); 298 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote); 299 300 if (!UseSoftFloat) { 301 // SSE has no i16 to fp conversion, only i32 302 if (X86ScalarSSEf32) { 303 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 304 // f32 and f64 cases are Legal, f80 case is not 305 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 306 } else { 307 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom); 308 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 309 } 310 } else { 311 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 312 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote); 313 } 314 315 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64 316 // are Legal, f80 is custom lowered. 317 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom); 318 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom); 319 320 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have 321 // this operation. 322 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote); 323 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote); 324 325 if (X86ScalarSSEf32) { 326 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote); 327 // f32 and f64 cases are Legal, f80 case is not 328 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 329 } else { 330 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom); 331 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 332 } 333 334 // Handle FP_TO_UINT by promoting the destination to a larger signed 335 // conversion. 336 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote); 337 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote); 338 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote); 339 340 if (Subtarget->is64Bit()) { 341 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand); 342 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote); 343 } else if (!UseSoftFloat) { 344 if (X86ScalarSSEf32 && !Subtarget->hasSSE3()) 345 // Expand FP_TO_UINT into a select. 346 // FIXME: We would like to use a Custom expander here eventually to do 347 // the optimal thing for SSE vs. the default expansion in the legalizer. 348 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand); 349 else 350 // With SSE3 we can use fisttpll to convert to a signed i64; without 351 // SSE, we're stuck with a fistpll. 352 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom); 353 } 354 355 // TODO: when we have SSE, these could be more efficient, by using movd/movq. 356 if (!X86ScalarSSEf64) { 357 setOperationAction(ISD::BITCAST , MVT::f32 , Expand); 358 setOperationAction(ISD::BITCAST , MVT::i32 , Expand); 359 if (Subtarget->is64Bit()) { 360 setOperationAction(ISD::BITCAST , MVT::f64 , Expand); 361 // Without SSE, i64->f64 goes through memory. 362 setOperationAction(ISD::BITCAST , MVT::i64 , Expand); 363 } 364 } 365 366 // Scalar integer divide and remainder are lowered to use operations that 367 // produce two results, to match the available instructions. This exposes 368 // the two-result form to trivial CSE, which is able to combine x/y and x%y 369 // into a single instruction. 370 // 371 // Scalar integer multiply-high is also lowered to use two-result 372 // operations, to match the available instructions. However, plain multiply 373 // (low) operations are left as Legal, as there are single-result 374 // instructions for this in x86. Using the two-result multiply instructions 375 // when both high and low results are needed must be arranged by dagcombine. 376 for (unsigned i = 0, e = 4; i != e; ++i) { 377 MVT VT = IntVTs[i]; 378 setOperationAction(ISD::MULHS, VT, Expand); 379 setOperationAction(ISD::MULHU, VT, Expand); 380 setOperationAction(ISD::SDIV, VT, Expand); 381 setOperationAction(ISD::UDIV, VT, Expand); 382 setOperationAction(ISD::SREM, VT, Expand); 383 setOperationAction(ISD::UREM, VT, Expand); 384 385 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences. 386 setOperationAction(ISD::ADDC, VT, Custom); 387 setOperationAction(ISD::ADDE, VT, Custom); 388 setOperationAction(ISD::SUBC, VT, Custom); 389 setOperationAction(ISD::SUBE, VT, Custom); 390 } 391 392 setOperationAction(ISD::BR_JT , MVT::Other, Expand); 393 setOperationAction(ISD::BRCOND , MVT::Other, Custom); 394 setOperationAction(ISD::BR_CC , MVT::Other, Expand); 395 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand); 396 if (Subtarget->is64Bit()) 397 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 398 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal); 399 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal); 400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand); 401 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand); 402 setOperationAction(ISD::FREM , MVT::f32 , Expand); 403 setOperationAction(ISD::FREM , MVT::f64 , Expand); 404 setOperationAction(ISD::FREM , MVT::f80 , Expand); 405 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom); 406 407 setOperationAction(ISD::CTTZ , MVT::i8 , Custom); 408 setOperationAction(ISD::CTLZ , MVT::i8 , Custom); 409 setOperationAction(ISD::CTTZ , MVT::i16 , Custom); 410 setOperationAction(ISD::CTLZ , MVT::i16 , Custom); 411 setOperationAction(ISD::CTTZ , MVT::i32 , Custom); 412 setOperationAction(ISD::CTLZ , MVT::i32 , Custom); 413 if (Subtarget->is64Bit()) { 414 setOperationAction(ISD::CTTZ , MVT::i64 , Custom); 415 setOperationAction(ISD::CTLZ , MVT::i64 , Custom); 416 } 417 418 if (Subtarget->hasPOPCNT()) { 419 setOperationAction(ISD::CTPOP , MVT::i8 , Promote); 420 } else { 421 setOperationAction(ISD::CTPOP , MVT::i8 , Expand); 422 setOperationAction(ISD::CTPOP , MVT::i16 , Expand); 423 setOperationAction(ISD::CTPOP , MVT::i32 , Expand); 424 if (Subtarget->is64Bit()) 425 setOperationAction(ISD::CTPOP , MVT::i64 , Expand); 426 } 427 428 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom); 429 setOperationAction(ISD::BSWAP , MVT::i16 , Expand); 430 431 // These should be promoted to a larger select which is supported. 432 setOperationAction(ISD::SELECT , MVT::i1 , Promote); 433 // X86 wants to expand cmov itself. 434 setOperationAction(ISD::SELECT , MVT::i8 , Custom); 435 setOperationAction(ISD::SELECT , MVT::i16 , Custom); 436 setOperationAction(ISD::SELECT , MVT::i32 , Custom); 437 setOperationAction(ISD::SELECT , MVT::f32 , Custom); 438 setOperationAction(ISD::SELECT , MVT::f64 , Custom); 439 setOperationAction(ISD::SELECT , MVT::f80 , Custom); 440 setOperationAction(ISD::SETCC , MVT::i8 , Custom); 441 setOperationAction(ISD::SETCC , MVT::i16 , Custom); 442 setOperationAction(ISD::SETCC , MVT::i32 , Custom); 443 setOperationAction(ISD::SETCC , MVT::f32 , Custom); 444 setOperationAction(ISD::SETCC , MVT::f64 , Custom); 445 setOperationAction(ISD::SETCC , MVT::f80 , Custom); 446 if (Subtarget->is64Bit()) { 447 setOperationAction(ISD::SELECT , MVT::i64 , Custom); 448 setOperationAction(ISD::SETCC , MVT::i64 , Custom); 449 } 450 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom); 451 452 // Darwin ABI issue. 453 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom); 454 setOperationAction(ISD::JumpTable , MVT::i32 , Custom); 455 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom); 456 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom); 457 if (Subtarget->is64Bit()) 458 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 459 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom); 460 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom); 461 if (Subtarget->is64Bit()) { 462 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom); 463 setOperationAction(ISD::JumpTable , MVT::i64 , Custom); 464 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom); 465 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom); 466 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom); 467 } 468 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86) 469 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom); 470 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom); 471 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom); 472 if (Subtarget->is64Bit()) { 473 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom); 474 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom); 475 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom); 476 } 477 478 if (Subtarget->hasXMM()) 479 setOperationAction(ISD::PREFETCH , MVT::Other, Legal); 480 481 // We may not have a libcall for MEMBARRIER so we should lower this. 482 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom); 483 484 // On X86 and X86-64, atomic operations are lowered to locked instructions. 485 // Locked instructions, in turn, have implicit fence semantics (all memory 486 // operations are flushed before issuing the locked instruction, and they 487 // are not buffered), so we can fold away the common pattern of 488 // fence-atomic-fence. 489 setShouldFoldAtomicFences(true); 490 491 // Expand certain atomics 492 for (unsigned i = 0, e = 4; i != e; ++i) { 493 MVT VT = IntVTs[i]; 494 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom); 495 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 496 } 497 498 if (!Subtarget->is64Bit()) { 499 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom); 500 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 501 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 502 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom); 503 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom); 504 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom); 505 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom); 506 } 507 508 // FIXME - use subtarget debug flags 509 if (!Subtarget->isTargetDarwin() && 510 !Subtarget->isTargetELF() && 511 !Subtarget->isTargetCygMing()) { 512 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); 513 } 514 515 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand); 516 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand); 517 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand); 518 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand); 519 if (Subtarget->is64Bit()) { 520 setExceptionPointerRegister(X86::RAX); 521 setExceptionSelectorRegister(X86::RDX); 522 } else { 523 setExceptionPointerRegister(X86::EAX); 524 setExceptionSelectorRegister(X86::EDX); 525 } 526 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom); 527 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom); 528 529 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom); 530 531 setOperationAction(ISD::TRAP, MVT::Other, Legal); 532 533 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 534 setOperationAction(ISD::VASTART , MVT::Other, Custom); 535 setOperationAction(ISD::VAEND , MVT::Other, Expand); 536 if (Subtarget->is64Bit()) { 537 setOperationAction(ISD::VAARG , MVT::Other, Custom); 538 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 539 } else { 540 setOperationAction(ISD::VAARG , MVT::Other, Expand); 541 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 542 } 543 544 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 545 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 546 if (Subtarget->is64Bit()) 547 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 548 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) 549 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 550 else 551 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 552 553 if (!UseSoftFloat && X86ScalarSSEf64) { 554 // f32 and f64 use SSE. 555 // Set up the FP register classes. 556 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 557 addRegisterClass(MVT::f64, X86::FR64RegisterClass); 558 559 // Use ANDPD to simulate FABS. 560 setOperationAction(ISD::FABS , MVT::f64, Custom); 561 setOperationAction(ISD::FABS , MVT::f32, Custom); 562 563 // Use XORP to simulate FNEG. 564 setOperationAction(ISD::FNEG , MVT::f64, Custom); 565 setOperationAction(ISD::FNEG , MVT::f32, Custom); 566 567 // Use ANDPD and ORPD to simulate FCOPYSIGN. 568 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 569 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 570 571 // We don't support sin/cos/fmod 572 setOperationAction(ISD::FSIN , MVT::f64, Expand); 573 setOperationAction(ISD::FCOS , MVT::f64, Expand); 574 setOperationAction(ISD::FSIN , MVT::f32, Expand); 575 setOperationAction(ISD::FCOS , MVT::f32, Expand); 576 577 // Expand FP immediates into loads from the stack, except for the special 578 // cases we handle. 579 addLegalFPImmediate(APFloat(+0.0)); // xorpd 580 addLegalFPImmediate(APFloat(+0.0f)); // xorps 581 } else if (!UseSoftFloat && X86ScalarSSEf32) { 582 // Use SSE for f32, x87 for f64. 583 // Set up the FP register classes. 584 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 585 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 586 587 // Use ANDPS to simulate FABS. 588 setOperationAction(ISD::FABS , MVT::f32, Custom); 589 590 // Use XORP to simulate FNEG. 591 setOperationAction(ISD::FNEG , MVT::f32, Custom); 592 593 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 594 595 // Use ANDPS and ORPS to simulate FCOPYSIGN. 596 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 597 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 598 599 // We don't support sin/cos/fmod 600 setOperationAction(ISD::FSIN , MVT::f32, Expand); 601 setOperationAction(ISD::FCOS , MVT::f32, Expand); 602 603 // Special cases we handle for FP constants. 604 addLegalFPImmediate(APFloat(+0.0f)); // xorps 605 addLegalFPImmediate(APFloat(+0.0)); // FLD0 606 addLegalFPImmediate(APFloat(+1.0)); // FLD1 607 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 608 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 609 610 if (!UnsafeFPMath) { 611 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 612 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 613 } 614 } else if (!UseSoftFloat) { 615 // f32 and f64 in x87. 616 // Set up the FP register classes. 617 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 618 addRegisterClass(MVT::f32, X86::RFP32RegisterClass); 619 620 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 621 setOperationAction(ISD::UNDEF, MVT::f32, Expand); 622 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 623 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 624 625 if (!UnsafeFPMath) { 626 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 627 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 628 } 629 addLegalFPImmediate(APFloat(+0.0)); // FLD0 630 addLegalFPImmediate(APFloat(+1.0)); // FLD1 631 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 632 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 633 addLegalFPImmediate(APFloat(+0.0f)); // FLD0 634 addLegalFPImmediate(APFloat(+1.0f)); // FLD1 635 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS 636 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS 637 } 638 639 // Long double always uses X87. 640 if (!UseSoftFloat) { 641 addRegisterClass(MVT::f80, X86::RFP80RegisterClass); 642 setOperationAction(ISD::UNDEF, MVT::f80, Expand); 643 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand); 644 { 645 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended); 646 addLegalFPImmediate(TmpFlt); // FLD0 647 TmpFlt.changeSign(); 648 addLegalFPImmediate(TmpFlt); // FLD0/FCHS 649 650 bool ignored; 651 APFloat TmpFlt2(+1.0); 652 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, 653 &ignored); 654 addLegalFPImmediate(TmpFlt2); // FLD1 655 TmpFlt2.changeSign(); 656 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS 657 } 658 659 if (!UnsafeFPMath) { 660 setOperationAction(ISD::FSIN , MVT::f80 , Expand); 661 setOperationAction(ISD::FCOS , MVT::f80 , Expand); 662 } 663 } 664 665 // Always use a library call for pow. 666 setOperationAction(ISD::FPOW , MVT::f32 , Expand); 667 setOperationAction(ISD::FPOW , MVT::f64 , Expand); 668 setOperationAction(ISD::FPOW , MVT::f80 , Expand); 669 670 setOperationAction(ISD::FLOG, MVT::f80, Expand); 671 setOperationAction(ISD::FLOG2, MVT::f80, Expand); 672 setOperationAction(ISD::FLOG10, MVT::f80, Expand); 673 setOperationAction(ISD::FEXP, MVT::f80, Expand); 674 setOperationAction(ISD::FEXP2, MVT::f80, Expand); 675 676 // First set operation action for all vector types to either promote 677 // (for widening) or expand (for scalarization). Then we will selectively 678 // turn on ones that can be effectively codegen'd. 679 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 680 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) { 681 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand); 682 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand); 683 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand); 684 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand); 685 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand); 686 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand); 687 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand); 688 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand); 689 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand); 690 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand); 691 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand); 692 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand); 693 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand); 694 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand); 695 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand); 696 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand); 697 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 698 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 699 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand); 700 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand); 701 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand); 702 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand); 703 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand); 704 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand); 705 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand); 706 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 707 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 708 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand); 709 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand); 710 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand); 711 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand); 712 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand); 713 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand); 714 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand); 715 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand); 716 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand); 717 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand); 718 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand); 719 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand); 720 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand); 721 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand); 722 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand); 723 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand); 724 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand); 725 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand); 726 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand); 727 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand); 728 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 729 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 730 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand); 731 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand); 732 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand); 733 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand); 734 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand); 735 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 736 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 737 setTruncStoreAction((MVT::SimpleValueType)VT, 738 (MVT::SimpleValueType)InnerVT, Expand); 739 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand); 740 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand); 741 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand); 742 } 743 744 // FIXME: In order to prevent SSE instructions being expanded to MMX ones 745 // with -msoft-float, disable use of MMX as well. 746 if (!UseSoftFloat && Subtarget->hasMMX()) { 747 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass); 748 // No operations on x86mmx supported, everything uses intrinsics. 749 } 750 751 // MMX-sized vectors (other than x86mmx) are expected to be expanded 752 // into smaller operations. 753 setOperationAction(ISD::MULHS, MVT::v8i8, Expand); 754 setOperationAction(ISD::MULHS, MVT::v4i16, Expand); 755 setOperationAction(ISD::MULHS, MVT::v2i32, Expand); 756 setOperationAction(ISD::MULHS, MVT::v1i64, Expand); 757 setOperationAction(ISD::AND, MVT::v8i8, Expand); 758 setOperationAction(ISD::AND, MVT::v4i16, Expand); 759 setOperationAction(ISD::AND, MVT::v2i32, Expand); 760 setOperationAction(ISD::AND, MVT::v1i64, Expand); 761 setOperationAction(ISD::OR, MVT::v8i8, Expand); 762 setOperationAction(ISD::OR, MVT::v4i16, Expand); 763 setOperationAction(ISD::OR, MVT::v2i32, Expand); 764 setOperationAction(ISD::OR, MVT::v1i64, Expand); 765 setOperationAction(ISD::XOR, MVT::v8i8, Expand); 766 setOperationAction(ISD::XOR, MVT::v4i16, Expand); 767 setOperationAction(ISD::XOR, MVT::v2i32, Expand); 768 setOperationAction(ISD::XOR, MVT::v1i64, Expand); 769 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand); 770 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand); 771 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand); 772 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand); 773 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand); 774 setOperationAction(ISD::SELECT, MVT::v8i8, Expand); 775 setOperationAction(ISD::SELECT, MVT::v4i16, Expand); 776 setOperationAction(ISD::SELECT, MVT::v2i32, Expand); 777 setOperationAction(ISD::SELECT, MVT::v1i64, Expand); 778 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand); 779 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand); 780 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand); 781 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand); 782 783 if (!UseSoftFloat && Subtarget->hasXMM()) { 784 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass); 785 786 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 787 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 788 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 789 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 790 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 791 setOperationAction(ISD::FNEG, MVT::v4f32, Custom); 792 setOperationAction(ISD::LOAD, MVT::v4f32, Legal); 793 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 794 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom); 795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 796 setOperationAction(ISD::SELECT, MVT::v4f32, Custom); 797 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom); 798 } 799 800 if (!UseSoftFloat && Subtarget->hasXMMInt()) { 801 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass); 802 803 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM 804 // registers cannot be used even for integer operations. 805 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass); 806 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass); 807 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass); 808 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass); 809 810 setOperationAction(ISD::ADD, MVT::v16i8, Legal); 811 setOperationAction(ISD::ADD, MVT::v8i16, Legal); 812 setOperationAction(ISD::ADD, MVT::v4i32, Legal); 813 setOperationAction(ISD::ADD, MVT::v2i64, Legal); 814 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 815 setOperationAction(ISD::SUB, MVT::v16i8, Legal); 816 setOperationAction(ISD::SUB, MVT::v8i16, Legal); 817 setOperationAction(ISD::SUB, MVT::v4i32, Legal); 818 setOperationAction(ISD::SUB, MVT::v2i64, Legal); 819 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 820 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 821 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 822 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 823 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 824 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 825 setOperationAction(ISD::FNEG, MVT::v2f64, Custom); 826 827 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom); 828 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom); 829 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom); 830 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom); 831 832 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom); 833 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom); 834 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 835 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 837 838 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom); 839 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom); 840 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom); 841 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom); 842 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom); 843 844 // Custom lower build_vector, vector_shuffle, and extract_vector_elt. 845 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) { 846 EVT VT = (MVT::SimpleValueType)i; 847 // Do not attempt to custom lower non-power-of-2 vectors 848 if (!isPowerOf2_32(VT.getVectorNumElements())) 849 continue; 850 // Do not attempt to custom lower non-128-bit vectors 851 if (!VT.is128BitVector()) 852 continue; 853 setOperationAction(ISD::BUILD_VECTOR, 854 VT.getSimpleVT().SimpleTy, Custom); 855 setOperationAction(ISD::VECTOR_SHUFFLE, 856 VT.getSimpleVT().SimpleTy, Custom); 857 setOperationAction(ISD::EXTRACT_VECTOR_ELT, 858 VT.getSimpleVT().SimpleTy, Custom); 859 } 860 861 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 862 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 863 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 864 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 865 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 866 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 867 868 if (Subtarget->is64Bit()) { 869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 870 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 871 } 872 873 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 874 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) { 875 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 876 EVT VT = SVT; 877 878 // Do not attempt to promote non-128-bit vectors 879 if (!VT.is128BitVector()) 880 continue; 881 882 setOperationAction(ISD::AND, SVT, Promote); 883 AddPromotedToType (ISD::AND, SVT, MVT::v2i64); 884 setOperationAction(ISD::OR, SVT, Promote); 885 AddPromotedToType (ISD::OR, SVT, MVT::v2i64); 886 setOperationAction(ISD::XOR, SVT, Promote); 887 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64); 888 setOperationAction(ISD::LOAD, SVT, Promote); 889 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64); 890 setOperationAction(ISD::SELECT, SVT, Promote); 891 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64); 892 } 893 894 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 895 896 // Custom lower v2i64 and v2f64 selects. 897 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 898 setOperationAction(ISD::LOAD, MVT::v2i64, Legal); 899 setOperationAction(ISD::SELECT, MVT::v2f64, Custom); 900 setOperationAction(ISD::SELECT, MVT::v2i64, Custom); 901 902 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 903 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 904 } 905 906 if (Subtarget->hasSSE41()) { 907 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 908 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 909 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 910 setOperationAction(ISD::FRINT, MVT::f32, Legal); 911 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 912 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 913 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 914 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 915 setOperationAction(ISD::FRINT, MVT::f64, Legal); 916 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 917 918 // FIXME: Do we need to handle scalar-to-vector here? 919 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 920 921 // Can turn SHL into an integer multiply. 922 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 923 setOperationAction(ISD::SHL, MVT::v16i8, Custom); 924 925 // i8 and i16 vectors are custom , because the source register and source 926 // source memory operand types are not the same width. f32 vectors are 927 // custom since the immediate controlling the insert encodes additional 928 // information. 929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 930 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 931 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 932 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 933 934 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom); 935 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom); 936 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom); 937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 938 939 if (Subtarget->is64Bit()) { 940 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal); 941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 942 } 943 } 944 945 if (Subtarget->hasSSE42()) 946 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom); 947 948 if (!UseSoftFloat && Subtarget->hasAVX()) { 949 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass); 950 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass); 951 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass); 952 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass); 953 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass); 954 955 setOperationAction(ISD::LOAD, MVT::v8f32, Legal); 956 setOperationAction(ISD::LOAD, MVT::v8i32, Legal); 957 setOperationAction(ISD::LOAD, MVT::v4f64, Legal); 958 setOperationAction(ISD::LOAD, MVT::v4i64, Legal); 959 960 setOperationAction(ISD::FADD, MVT::v8f32, Legal); 961 setOperationAction(ISD::FSUB, MVT::v8f32, Legal); 962 setOperationAction(ISD::FMUL, MVT::v8f32, Legal); 963 setOperationAction(ISD::FDIV, MVT::v8f32, Legal); 964 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal); 965 setOperationAction(ISD::FNEG, MVT::v8f32, Custom); 966 967 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 968 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 969 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 970 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 971 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 972 setOperationAction(ISD::FNEG, MVT::v4f64, Custom); 973 974 // Custom lower build_vector, vector_shuffle, scalar_to_vector, 975 // insert_vector_elt extract_subvector and extract_vector_elt for 976 // 256-bit types. 977 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 978 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; 979 ++i) { 980 MVT::SimpleValueType VT = (MVT::SimpleValueType)i; 981 // Do not attempt to custom lower non-256-bit vectors 982 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()) 983 || (MVT(VT).getSizeInBits() < 256)) 984 continue; 985 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 986 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 987 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 989 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom); 990 } 991 // Custom-lower insert_subvector and extract_subvector based on 992 // the result type. 993 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 994 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; 995 ++i) { 996 MVT::SimpleValueType VT = (MVT::SimpleValueType)i; 997 // Do not attempt to custom lower non-256-bit vectors 998 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())) 999 continue; 1000 1001 if (MVT(VT).getSizeInBits() == 128) { 1002 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1003 } 1004 else if (MVT(VT).getSizeInBits() == 256) { 1005 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1006 } 1007 } 1008 1009 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64. 1010 // Don't promote loads because we need them for VPERM vector index versions. 1011 1012 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1013 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; 1014 VT++) { 1015 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements()) 1016 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256)) 1017 continue; 1018 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote); 1019 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64); 1020 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote); 1021 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64); 1022 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote); 1023 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64); 1024 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote); 1025 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64); 1026 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote); 1027 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64); 1028 } 1029 } 1030 1031 // We want to custom lower some of our intrinsics. 1032 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1033 1034 1035 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't 1036 // handle type legalization for these operations here. 1037 // 1038 // FIXME: We really should do custom legalization for addition and 1039 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better 1040 // than generic legalization for 64-bit multiplication-with-overflow, though. 1041 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) { 1042 // Add/Sub/Mul with overflow operations are custom lowered. 1043 MVT VT = IntVTs[i]; 1044 setOperationAction(ISD::SADDO, VT, Custom); 1045 setOperationAction(ISD::UADDO, VT, Custom); 1046 setOperationAction(ISD::SSUBO, VT, Custom); 1047 setOperationAction(ISD::USUBO, VT, Custom); 1048 setOperationAction(ISD::SMULO, VT, Custom); 1049 setOperationAction(ISD::UMULO, VT, Custom); 1050 } 1051 1052 // There are no 8-bit 3-address imul/mul instructions 1053 setOperationAction(ISD::SMULO, MVT::i8, Expand); 1054 setOperationAction(ISD::UMULO, MVT::i8, Expand); 1055 1056 if (!Subtarget->is64Bit()) { 1057 // These libcalls are not available in 32-bit. 1058 setLibcallName(RTLIB::SHL_I128, 0); 1059 setLibcallName(RTLIB::SRL_I128, 0); 1060 setLibcallName(RTLIB::SRA_I128, 0); 1061 } 1062 1063 // We have target-specific dag combine patterns for the following nodes: 1064 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1065 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 1066 setTargetDAGCombine(ISD::BUILD_VECTOR); 1067 setTargetDAGCombine(ISD::SELECT); 1068 setTargetDAGCombine(ISD::SHL); 1069 setTargetDAGCombine(ISD::SRA); 1070 setTargetDAGCombine(ISD::SRL); 1071 setTargetDAGCombine(ISD::OR); 1072 setTargetDAGCombine(ISD::AND); 1073 setTargetDAGCombine(ISD::ADD); 1074 setTargetDAGCombine(ISD::SUB); 1075 setTargetDAGCombine(ISD::STORE); 1076 setTargetDAGCombine(ISD::ZERO_EXTEND); 1077 if (Subtarget->is64Bit()) 1078 setTargetDAGCombine(ISD::MUL); 1079 1080 computeRegisterProperties(); 1081 1082 // On Darwin, -Os means optimize for size without hurting performance, 1083 // do not reduce the limit. 1084 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores 1085 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8; 1086 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores 1087 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1088 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores 1089 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1090 setPrefLoopAlignment(16); 1091 benefitFromCodePlacementOpt = true; 1092} 1093 1094 1095MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const { 1096 return MVT::i8; 1097} 1098 1099 1100/// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1101/// the desired ByVal argument alignment. 1102static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) { 1103 if (MaxAlign == 16) 1104 return; 1105 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1106 if (VTy->getBitWidth() == 128) 1107 MaxAlign = 16; 1108 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1109 unsigned EltAlign = 0; 1110 getMaxByValAlign(ATy->getElementType(), EltAlign); 1111 if (EltAlign > MaxAlign) 1112 MaxAlign = EltAlign; 1113 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) { 1114 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1115 unsigned EltAlign = 0; 1116 getMaxByValAlign(STy->getElementType(i), EltAlign); 1117 if (EltAlign > MaxAlign) 1118 MaxAlign = EltAlign; 1119 if (MaxAlign == 16) 1120 break; 1121 } 1122 } 1123 return; 1124} 1125 1126/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1127/// function arguments in the caller parameter area. For X86, aggregates 1128/// that contain SSE vectors are placed at 16-byte boundaries while the rest 1129/// are at 4-byte boundaries. 1130unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const { 1131 if (Subtarget->is64Bit()) { 1132 // Max of 8 and alignment of type. 1133 unsigned TyAlign = TD->getABITypeAlignment(Ty); 1134 if (TyAlign > 8) 1135 return TyAlign; 1136 return 8; 1137 } 1138 1139 unsigned Align = 4; 1140 if (Subtarget->hasXMM()) 1141 getMaxByValAlign(Ty, Align); 1142 return Align; 1143} 1144 1145/// getOptimalMemOpType - Returns the target specific optimal type for load 1146/// and store operations as a result of memset, memcpy, and memmove 1147/// lowering. If DstAlign is zero that means it's safe to destination 1148/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 1149/// means there isn't a need to check it against alignment requirement, 1150/// probably because the source does not need to be loaded. If 1151/// 'NonScalarIntSafe' is true, that means it's safe to return a 1152/// non-scalar-integer type, e.g. empty string source, constant, or loaded 1153/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is 1154/// constant so it does not need to be loaded. 1155/// It returns EVT::Other if the type should be determined using generic 1156/// target-independent logic. 1157EVT 1158X86TargetLowering::getOptimalMemOpType(uint64_t Size, 1159 unsigned DstAlign, unsigned SrcAlign, 1160 bool NonScalarIntSafe, 1161 bool MemcpyStrSrc, 1162 MachineFunction &MF) const { 1163 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like 1164 // linux. This is because the stack realignment code can't handle certain 1165 // cases like PR2962. This should be removed when PR2962 is fixed. 1166 const Function *F = MF.getFunction(); 1167 if (NonScalarIntSafe && 1168 !F->hasFnAttr(Attribute::NoImplicitFloat)) { 1169 if (Size >= 16 && 1170 (Subtarget->isUnalignedMemAccessFast() || 1171 ((DstAlign == 0 || DstAlign >= 16) && 1172 (SrcAlign == 0 || SrcAlign >= 16))) && 1173 Subtarget->getStackAlignment() >= 16) { 1174 if (Subtarget->hasSSE2()) 1175 return MVT::v4i32; 1176 if (Subtarget->hasSSE1()) 1177 return MVT::v4f32; 1178 } else if (!MemcpyStrSrc && Size >= 8 && 1179 !Subtarget->is64Bit() && 1180 Subtarget->getStackAlignment() >= 8 && 1181 Subtarget->hasXMMInt()) { 1182 // Do not use f64 to lower memcpy if source is string constant. It's 1183 // better to use i32 to avoid the loads. 1184 return MVT::f64; 1185 } 1186 } 1187 if (Subtarget->is64Bit() && Size >= 8) 1188 return MVT::i64; 1189 return MVT::i32; 1190} 1191 1192/// getJumpTableEncoding - Return the entry encoding for a jump table in the 1193/// current function. The returned value is a member of the 1194/// MachineJumpTableInfo::JTEntryKind enum. 1195unsigned X86TargetLowering::getJumpTableEncoding() const { 1196 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF 1197 // symbol. 1198 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1199 Subtarget->isPICStyleGOT()) 1200 return MachineJumpTableInfo::EK_Custom32; 1201 1202 // Otherwise, use the normal jump table encoding heuristics. 1203 return TargetLowering::getJumpTableEncoding(); 1204} 1205 1206const MCExpr * 1207X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 1208 const MachineBasicBlock *MBB, 1209 unsigned uid,MCContext &Ctx) const{ 1210 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1211 Subtarget->isPICStyleGOT()); 1212 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF 1213 // entries. 1214 return MCSymbolRefExpr::Create(MBB->getSymbol(), 1215 MCSymbolRefExpr::VK_GOTOFF, Ctx); 1216} 1217 1218/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 1219/// jumptable. 1220SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table, 1221 SelectionDAG &DAG) const { 1222 if (!Subtarget->is64Bit()) 1223 // This doesn't have DebugLoc associated with it, but is not really the 1224 // same as a Register. 1225 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy()); 1226 return Table; 1227} 1228 1229/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 1230/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 1231/// MCExpr. 1232const MCExpr *X86TargetLowering:: 1233getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, 1234 MCContext &Ctx) const { 1235 // X86-64 uses RIP relative addressing based on the jump table label. 1236 if (Subtarget->isPICStyleRIPRel()) 1237 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 1238 1239 // Otherwise, the reference is relative to the PIC base. 1240 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx); 1241} 1242 1243/// getFunctionAlignment - Return the Log2 alignment of this function. 1244unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const { 1245 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4; 1246} 1247 1248// FIXME: Why this routine is here? Move to RegInfo! 1249std::pair<const TargetRegisterClass*, uint8_t> 1250X86TargetLowering::findRepresentativeClass(EVT VT) const{ 1251 const TargetRegisterClass *RRC = 0; 1252 uint8_t Cost = 1; 1253 switch (VT.getSimpleVT().SimpleTy) { 1254 default: 1255 return TargetLowering::findRepresentativeClass(VT); 1256 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64: 1257 RRC = (Subtarget->is64Bit() 1258 ? X86::GR64RegisterClass : X86::GR32RegisterClass); 1259 break; 1260 case MVT::x86mmx: 1261 RRC = X86::VR64RegisterClass; 1262 break; 1263 case MVT::f32: case MVT::f64: 1264 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1265 case MVT::v4f32: case MVT::v2f64: 1266 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32: 1267 case MVT::v4f64: 1268 RRC = X86::VR128RegisterClass; 1269 break; 1270 } 1271 return std::make_pair(RRC, Cost); 1272} 1273 1274// FIXME: Why this routine is here? Move to RegInfo! 1275unsigned 1276X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC, 1277 MachineFunction &MF) const { 1278 const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering(); 1279 1280 unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0; 1281 switch (RC->getID()) { 1282 default: 1283 return 0; 1284 case X86::GR32RegClassID: 1285 return 4 - FPDiff; 1286 case X86::GR64RegClassID: 1287 return 8 - FPDiff; 1288 case X86::VR128RegClassID: 1289 return Subtarget->is64Bit() ? 10 : 4; 1290 case X86::VR64RegClassID: 1291 return 4; 1292 } 1293} 1294 1295bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace, 1296 unsigned &Offset) const { 1297 if (!Subtarget->isTargetLinux()) 1298 return false; 1299 1300 if (Subtarget->is64Bit()) { 1301 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs: 1302 Offset = 0x28; 1303 if (getTargetMachine().getCodeModel() == CodeModel::Kernel) 1304 AddressSpace = 256; 1305 else 1306 AddressSpace = 257; 1307 } else { 1308 // %gs:0x14 on i386 1309 Offset = 0x14; 1310 AddressSpace = 256; 1311 } 1312 return true; 1313} 1314 1315 1316//===----------------------------------------------------------------------===// 1317// Return Value Calling Convention Implementation 1318//===----------------------------------------------------------------------===// 1319 1320#include "X86GenCallingConv.inc" 1321 1322bool 1323X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg, 1324 const SmallVectorImpl<ISD::OutputArg> &Outs, 1325 LLVMContext &Context) const { 1326 SmallVector<CCValAssign, 16> RVLocs; 1327 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), 1328 RVLocs, Context); 1329 return CCInfo.CheckReturn(Outs, RetCC_X86); 1330} 1331 1332SDValue 1333X86TargetLowering::LowerReturn(SDValue Chain, 1334 CallingConv::ID CallConv, bool isVarArg, 1335 const SmallVectorImpl<ISD::OutputArg> &Outs, 1336 const SmallVectorImpl<SDValue> &OutVals, 1337 DebugLoc dl, SelectionDAG &DAG) const { 1338 MachineFunction &MF = DAG.getMachineFunction(); 1339 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1340 1341 SmallVector<CCValAssign, 16> RVLocs; 1342 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), 1343 RVLocs, *DAG.getContext()); 1344 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1345 1346 // Add the regs to the liveout set for the function. 1347 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1348 for (unsigned i = 0; i != RVLocs.size(); ++i) 1349 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg())) 1350 MRI.addLiveOut(RVLocs[i].getLocReg()); 1351 1352 SDValue Flag; 1353 1354 SmallVector<SDValue, 6> RetOps; 1355 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1356 // Operand #1 = Bytes To Pop 1357 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), 1358 MVT::i16)); 1359 1360 // Copy the result values into the output registers. 1361 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1362 CCValAssign &VA = RVLocs[i]; 1363 assert(VA.isRegLoc() && "Can only return in registers!"); 1364 SDValue ValToCopy = OutVals[i]; 1365 EVT ValVT = ValToCopy.getValueType(); 1366 1367 // If this is x86-64, and we disabled SSE, we can't return FP values, 1368 // or SSE or MMX vectors. 1369 if ((ValVT == MVT::f32 || ValVT == MVT::f64 || 1370 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && 1371 (Subtarget->is64Bit() && !Subtarget->hasXMM())) { 1372 report_fatal_error("SSE register return with SSE disabled"); 1373 } 1374 // Likewise we can't return F64 values with SSE1 only. gcc does so, but 1375 // llvm-gcc has never done it right and no one has noticed, so this 1376 // should be OK for now. 1377 if (ValVT == MVT::f64 && 1378 (Subtarget->is64Bit() && !Subtarget->hasXMMInt())) 1379 report_fatal_error("SSE2 register return with SSE2 disabled"); 1380 1381 // Returns in ST0/ST1 are handled specially: these are pushed as operands to 1382 // the RET instruction and handled by the FP Stackifier. 1383 if (VA.getLocReg() == X86::ST0 || 1384 VA.getLocReg() == X86::ST1) { 1385 // If this is a copy from an xmm register to ST(0), use an FPExtend to 1386 // change the value to the FP stack register class. 1387 if (isScalarFPTypeInSSEReg(VA.getValVT())) 1388 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy); 1389 RetOps.push_back(ValToCopy); 1390 // Don't emit a copytoreg. 1391 continue; 1392 } 1393 1394 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64 1395 // which is returned in RAX / RDX. 1396 if (Subtarget->is64Bit()) { 1397 if (ValVT == MVT::x86mmx) { 1398 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1399 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy); 1400 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 1401 ValToCopy); 1402 // If we don't have SSE2 available, convert to v4f32 so the generated 1403 // register is legal. 1404 if (!Subtarget->hasSSE2()) 1405 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy); 1406 } 1407 } 1408 } 1409 1410 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag); 1411 Flag = Chain.getValue(1); 1412 } 1413 1414 // The x86-64 ABI for returning structs by value requires that we copy 1415 // the sret argument into %rax for the return. We saved the argument into 1416 // a virtual register in the entry block, so now we copy the value out 1417 // and into %rax. 1418 if (Subtarget->is64Bit() && 1419 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) { 1420 MachineFunction &MF = DAG.getMachineFunction(); 1421 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1422 unsigned Reg = FuncInfo->getSRetReturnReg(); 1423 assert(Reg && 1424 "SRetReturnReg should have been set in LowerFormalArguments()."); 1425 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy()); 1426 1427 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag); 1428 Flag = Chain.getValue(1); 1429 1430 // RAX now acts like a return value. 1431 MRI.addLiveOut(X86::RAX); 1432 } 1433 1434 RetOps[0] = Chain; // Update chain. 1435 1436 // Add the flag if we have it. 1437 if (Flag.getNode()) 1438 RetOps.push_back(Flag); 1439 1440 return DAG.getNode(X86ISD::RET_FLAG, dl, 1441 MVT::Other, &RetOps[0], RetOps.size()); 1442} 1443 1444bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const { 1445 if (N->getNumValues() != 1) 1446 return false; 1447 if (!N->hasNUsesOfValue(1, 0)) 1448 return false; 1449 1450 SDNode *Copy = *N->use_begin(); 1451 if (Copy->getOpcode() != ISD::CopyToReg && 1452 Copy->getOpcode() != ISD::FP_EXTEND) 1453 return false; 1454 1455 bool HasRet = false; 1456 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 1457 UI != UE; ++UI) { 1458 if (UI->getOpcode() != X86ISD::RET_FLAG) 1459 return false; 1460 HasRet = true; 1461 } 1462 1463 return HasRet; 1464} 1465 1466/// LowerCallResult - Lower the result values of a call into the 1467/// appropriate copies out of appropriate physical registers. 1468/// 1469SDValue 1470X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1471 CallingConv::ID CallConv, bool isVarArg, 1472 const SmallVectorImpl<ISD::InputArg> &Ins, 1473 DebugLoc dl, SelectionDAG &DAG, 1474 SmallVectorImpl<SDValue> &InVals) const { 1475 1476 // Assign locations to each value returned by this call. 1477 SmallVector<CCValAssign, 16> RVLocs; 1478 bool Is64Bit = Subtarget->is64Bit(); 1479 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), 1480 RVLocs, *DAG.getContext()); 1481 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 1482 1483 // Copy all of the result registers out of their specified physreg. 1484 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1485 CCValAssign &VA = RVLocs[i]; 1486 EVT CopyVT = VA.getValVT(); 1487 1488 // If this is x86-64, and we disabled SSE, we can't return FP values 1489 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 1490 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) { 1491 report_fatal_error("SSE register return with SSE disabled"); 1492 } 1493 1494 SDValue Val; 1495 1496 // If this is a call to a function that returns an fp value on the floating 1497 // point stack, we must guarantee the the value is popped from the stack, so 1498 // a CopyFromReg is not good enough - the copy instruction may be eliminated 1499 // if the return value is not used. We use the FpGET_ST0 instructions 1500 // instead. 1501 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 1502 // If we prefer to use the value in xmm registers, copy it out as f80 and 1503 // use a truncate to move it from fp stack reg to xmm reg. 1504 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80; 1505 bool isST0 = VA.getLocReg() == X86::ST0; 1506 unsigned Opc = 0; 1507 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32; 1508 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64; 1509 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80; 1510 SDValue Ops[] = { Chain, InFlag }; 1511 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue, 1512 Ops, 2), 1); 1513 Val = Chain.getValue(0); 1514 1515 // Round the f80 to the right size, which also moves it to the appropriate 1516 // xmm register. 1517 if (CopyVT != VA.getValVT()) 1518 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val, 1519 // This truncation won't change the value. 1520 DAG.getIntPtrConstant(1)); 1521 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) { 1522 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64. 1523 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1524 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1525 MVT::v2i64, InFlag).getValue(1); 1526 Val = Chain.getValue(0); 1527 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, 1528 Val, DAG.getConstant(0, MVT::i64)); 1529 } else { 1530 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1531 MVT::i64, InFlag).getValue(1); 1532 Val = Chain.getValue(0); 1533 } 1534 Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val); 1535 } else { 1536 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1537 CopyVT, InFlag).getValue(1); 1538 Val = Chain.getValue(0); 1539 } 1540 InFlag = Chain.getValue(2); 1541 InVals.push_back(Val); 1542 } 1543 1544 return Chain; 1545} 1546 1547 1548//===----------------------------------------------------------------------===// 1549// C & StdCall & Fast Calling Convention implementation 1550//===----------------------------------------------------------------------===// 1551// StdCall calling convention seems to be standard for many Windows' API 1552// routines and around. It differs from C calling convention just a little: 1553// callee should clean up the stack, not caller. Symbols should be also 1554// decorated in some fancy way :) It doesn't support any vector arguments. 1555// For info on fast calling convention see Fast Calling Convention (tail call) 1556// implementation LowerX86_32FastCCCallTo. 1557 1558/// CallIsStructReturn - Determines whether a call uses struct return 1559/// semantics. 1560static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) { 1561 if (Outs.empty()) 1562 return false; 1563 1564 return Outs[0].Flags.isSRet(); 1565} 1566 1567/// ArgsAreStructReturn - Determines whether a function uses struct 1568/// return semantics. 1569static bool 1570ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) { 1571 if (Ins.empty()) 1572 return false; 1573 1574 return Ins[0].Flags.isSRet(); 1575} 1576 1577/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 1578/// by "Src" to address "Dst" with size and alignment information specified by 1579/// the specific parameter attribute. The copy will be passed as a byval 1580/// function parameter. 1581static SDValue 1582CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 1583 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 1584 DebugLoc dl) { 1585 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 1586 1587 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 1588 /*isVolatile*/false, /*AlwaysInline=*/true, 1589 MachinePointerInfo(), MachinePointerInfo()); 1590} 1591 1592/// IsTailCallConvention - Return true if the calling convention is one that 1593/// supports tail call optimization. 1594static bool IsTailCallConvention(CallingConv::ID CC) { 1595 return (CC == CallingConv::Fast || CC == CallingConv::GHC); 1596} 1597 1598/// FuncIsMadeTailCallSafe - Return true if the function is being made into 1599/// a tailcall target by changing its ABI. 1600static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) { 1601 return GuaranteedTailCallOpt && IsTailCallConvention(CC); 1602} 1603 1604SDValue 1605X86TargetLowering::LowerMemArgument(SDValue Chain, 1606 CallingConv::ID CallConv, 1607 const SmallVectorImpl<ISD::InputArg> &Ins, 1608 DebugLoc dl, SelectionDAG &DAG, 1609 const CCValAssign &VA, 1610 MachineFrameInfo *MFI, 1611 unsigned i) const { 1612 // Create the nodes corresponding to a load from this parameter slot. 1613 ISD::ArgFlagsTy Flags = Ins[i].Flags; 1614 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv); 1615 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal(); 1616 EVT ValVT; 1617 1618 // If value is passed by pointer we have address passed instead of the value 1619 // itself. 1620 if (VA.getLocInfo() == CCValAssign::Indirect) 1621 ValVT = VA.getLocVT(); 1622 else 1623 ValVT = VA.getValVT(); 1624 1625 // FIXME: For now, all byval parameter objects are marked mutable. This can be 1626 // changed with more analysis. 1627 // In case of tail call optimization mark all arguments mutable. Since they 1628 // could be overwritten by lowering of arguments in case of a tail call. 1629 if (Flags.isByVal()) { 1630 int FI = MFI->CreateFixedObject(Flags.getByValSize(), 1631 VA.getLocMemOffset(), isImmutable); 1632 return DAG.getFrameIndex(FI, getPointerTy()); 1633 } else { 1634 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8, 1635 VA.getLocMemOffset(), isImmutable); 1636 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 1637 return DAG.getLoad(ValVT, dl, Chain, FIN, 1638 MachinePointerInfo::getFixedStack(FI), 1639 false, false, 0); 1640 } 1641} 1642 1643SDValue 1644X86TargetLowering::LowerFormalArguments(SDValue Chain, 1645 CallingConv::ID CallConv, 1646 bool isVarArg, 1647 const SmallVectorImpl<ISD::InputArg> &Ins, 1648 DebugLoc dl, 1649 SelectionDAG &DAG, 1650 SmallVectorImpl<SDValue> &InVals) 1651 const { 1652 MachineFunction &MF = DAG.getMachineFunction(); 1653 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1654 1655 const Function* Fn = MF.getFunction(); 1656 if (Fn->hasExternalLinkage() && 1657 Subtarget->isTargetCygMing() && 1658 Fn->getName() == "main") 1659 FuncInfo->setForceFramePointer(true); 1660 1661 MachineFrameInfo *MFI = MF.getFrameInfo(); 1662 bool Is64Bit = Subtarget->is64Bit(); 1663 bool IsWin64 = Subtarget->isTargetWin64(); 1664 1665 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1666 "Var args not supported with calling convention fastcc or ghc"); 1667 1668 // Assign locations to all of the incoming arguments. 1669 SmallVector<CCValAssign, 16> ArgLocs; 1670 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), 1671 ArgLocs, *DAG.getContext()); 1672 1673 // Allocate shadow area for Win64 1674 if (IsWin64) { 1675 CCInfo.AllocateStack(32, 8); 1676 } 1677 1678 CCInfo.AnalyzeFormalArguments(Ins, CC_X86); 1679 1680 unsigned LastVal = ~0U; 1681 SDValue ArgValue; 1682 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1683 CCValAssign &VA = ArgLocs[i]; 1684 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later 1685 // places. 1686 assert(VA.getValNo() != LastVal && 1687 "Don't support value assigned to multiple locs yet"); 1688 LastVal = VA.getValNo(); 1689 1690 if (VA.isRegLoc()) { 1691 EVT RegVT = VA.getLocVT(); 1692 TargetRegisterClass *RC = NULL; 1693 if (RegVT == MVT::i32) 1694 RC = X86::GR32RegisterClass; 1695 else if (Is64Bit && RegVT == MVT::i64) 1696 RC = X86::GR64RegisterClass; 1697 else if (RegVT == MVT::f32) 1698 RC = X86::FR32RegisterClass; 1699 else if (RegVT == MVT::f64) 1700 RC = X86::FR64RegisterClass; 1701 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256) 1702 RC = X86::VR256RegisterClass; 1703 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128) 1704 RC = X86::VR128RegisterClass; 1705 else if (RegVT == MVT::x86mmx) 1706 RC = X86::VR64RegisterClass; 1707 else 1708 llvm_unreachable("Unknown argument type!"); 1709 1710 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 1711 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 1712 1713 // If this is an 8 or 16-bit value, it is really passed promoted to 32 1714 // bits. Insert an assert[sz]ext to capture this, then truncate to the 1715 // right size. 1716 if (VA.getLocInfo() == CCValAssign::SExt) 1717 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 1718 DAG.getValueType(VA.getValVT())); 1719 else if (VA.getLocInfo() == CCValAssign::ZExt) 1720 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 1721 DAG.getValueType(VA.getValVT())); 1722 else if (VA.getLocInfo() == CCValAssign::BCvt) 1723 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 1724 1725 if (VA.isExtInLoc()) { 1726 // Handle MMX values passed in XMM regs. 1727 if (RegVT.isVector()) { 1728 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), 1729 ArgValue); 1730 } else 1731 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1732 } 1733 } else { 1734 assert(VA.isMemLoc()); 1735 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i); 1736 } 1737 1738 // If value is passed via pointer - do a load. 1739 if (VA.getLocInfo() == CCValAssign::Indirect) 1740 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, 1741 MachinePointerInfo(), false, false, 0); 1742 1743 InVals.push_back(ArgValue); 1744 } 1745 1746 // The x86-64 ABI for returning structs by value requires that we copy 1747 // the sret argument into %rax for the return. Save the argument into 1748 // a virtual register so that we can access it from the return points. 1749 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) { 1750 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1751 unsigned Reg = FuncInfo->getSRetReturnReg(); 1752 if (!Reg) { 1753 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64)); 1754 FuncInfo->setSRetReturnReg(Reg); 1755 } 1756 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]); 1757 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain); 1758 } 1759 1760 unsigned StackSize = CCInfo.getNextStackOffset(); 1761 // Align stack specially for tail calls. 1762 if (FuncIsMadeTailCallSafe(CallConv)) 1763 StackSize = GetAlignedArgumentStackSize(StackSize, DAG); 1764 1765 // If the function takes variable number of arguments, make a frame index for 1766 // the start of the first vararg value... for expansion of llvm.va_start. 1767 if (isVarArg) { 1768 if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall && 1769 CallConv != CallingConv::X86_ThisCall))) { 1770 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true)); 1771 } 1772 if (Is64Bit) { 1773 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0; 1774 1775 // FIXME: We should really autogenerate these arrays 1776 static const unsigned GPR64ArgRegsWin64[] = { 1777 X86::RCX, X86::RDX, X86::R8, X86::R9 1778 }; 1779 static const unsigned GPR64ArgRegs64Bit[] = { 1780 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9 1781 }; 1782 static const unsigned XMMArgRegs64Bit[] = { 1783 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 1784 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 1785 }; 1786 const unsigned *GPR64ArgRegs; 1787 unsigned NumXMMRegs = 0; 1788 1789 if (IsWin64) { 1790 // The XMM registers which might contain var arg parameters are shadowed 1791 // in their paired GPR. So we only need to save the GPR to their home 1792 // slots. 1793 TotalNumIntRegs = 4; 1794 GPR64ArgRegs = GPR64ArgRegsWin64; 1795 } else { 1796 TotalNumIntRegs = 6; TotalNumXMMRegs = 8; 1797 GPR64ArgRegs = GPR64ArgRegs64Bit; 1798 1799 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs); 1800 } 1801 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 1802 TotalNumIntRegs); 1803 1804 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat); 1805 assert(!(NumXMMRegs && !Subtarget->hasXMM()) && 1806 "SSE register cannot be used when SSE is disabled!"); 1807 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) && 1808 "SSE register cannot be used when SSE is disabled!"); 1809 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM()) 1810 // Kernel mode asks for SSE to be disabled, so don't push them 1811 // on the stack. 1812 TotalNumXMMRegs = 0; 1813 1814 if (IsWin64) { 1815 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering(); 1816 // Get to the caller-allocated home save location. Add 8 to account 1817 // for the return address. 1818 int HomeOffset = TFI.getOffsetOfLocalArea() + 8; 1819 FuncInfo->setRegSaveFrameIndex( 1820 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false)); 1821 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex()); 1822 } else { 1823 // For X86-64, if there are vararg parameters that are passed via 1824 // registers, then we must store them to their spots on the stack so they 1825 // may be loaded by deferencing the result of va_next. 1826 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8); 1827 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16); 1828 FuncInfo->setRegSaveFrameIndex( 1829 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16, 1830 false)); 1831 } 1832 1833 // Store the integer parameter registers. 1834 SmallVector<SDValue, 8> MemOps; 1835 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 1836 getPointerTy()); 1837 unsigned Offset = FuncInfo->getVarArgsGPOffset(); 1838 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) { 1839 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN, 1840 DAG.getIntPtrConstant(Offset)); 1841 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs], 1842 X86::GR64RegisterClass); 1843 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 1844 SDValue Store = 1845 DAG.getStore(Val.getValue(1), dl, Val, FIN, 1846 MachinePointerInfo::getFixedStack( 1847 FuncInfo->getRegSaveFrameIndex(), Offset), 1848 false, false, 0); 1849 MemOps.push_back(Store); 1850 Offset += 8; 1851 } 1852 1853 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) { 1854 // Now store the XMM (fp + vector) parameter registers. 1855 SmallVector<SDValue, 11> SaveXMMOps; 1856 SaveXMMOps.push_back(Chain); 1857 1858 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass); 1859 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8); 1860 SaveXMMOps.push_back(ALVal); 1861 1862 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1863 FuncInfo->getRegSaveFrameIndex())); 1864 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1865 FuncInfo->getVarArgsFPOffset())); 1866 1867 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) { 1868 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs], 1869 X86::VR128RegisterClass); 1870 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32); 1871 SaveXMMOps.push_back(Val); 1872 } 1873 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, 1874 MVT::Other, 1875 &SaveXMMOps[0], SaveXMMOps.size())); 1876 } 1877 1878 if (!MemOps.empty()) 1879 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 1880 &MemOps[0], MemOps.size()); 1881 } 1882 } 1883 1884 // Some CCs need callee pop. 1885 if (Subtarget->IsCalleePop(isVarArg, CallConv)) { 1886 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything. 1887 } else { 1888 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing. 1889 // If this is an sret function, the return should pop the hidden pointer. 1890 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins)) 1891 FuncInfo->setBytesToPopOnReturn(4); 1892 } 1893 1894 if (!Is64Bit) { 1895 // RegSaveFrameIndex is X86-64 only. 1896 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA); 1897 if (CallConv == CallingConv::X86_FastCall || 1898 CallConv == CallingConv::X86_ThisCall) 1899 // fastcc functions can't have varargs. 1900 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA); 1901 } 1902 1903 return Chain; 1904} 1905 1906SDValue 1907X86TargetLowering::LowerMemOpCallTo(SDValue Chain, 1908 SDValue StackPtr, SDValue Arg, 1909 DebugLoc dl, SelectionDAG &DAG, 1910 const CCValAssign &VA, 1911 ISD::ArgFlagsTy Flags) const { 1912 unsigned LocMemOffset = VA.getLocMemOffset(); 1913 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 1914 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 1915 if (Flags.isByVal()) 1916 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl); 1917 1918 return DAG.getStore(Chain, dl, Arg, PtrOff, 1919 MachinePointerInfo::getStack(LocMemOffset), 1920 false, false, 0); 1921} 1922 1923/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call 1924/// optimization is performed and it is required. 1925SDValue 1926X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 1927 SDValue &OutRetAddr, SDValue Chain, 1928 bool IsTailCall, bool Is64Bit, 1929 int FPDiff, DebugLoc dl) const { 1930 // Adjust the Return address stack slot. 1931 EVT VT = getPointerTy(); 1932 OutRetAddr = getReturnAddressFrameIndex(DAG); 1933 1934 // Load the "old" Return address. 1935 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(), 1936 false, false, 0); 1937 return SDValue(OutRetAddr.getNode(), 1); 1938} 1939 1940/// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call 1941/// optimization is performed and it is required (FPDiff!=0). 1942static SDValue 1943EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 1944 SDValue Chain, SDValue RetAddrFrIdx, 1945 bool Is64Bit, int FPDiff, DebugLoc dl) { 1946 // Store the return address to the appropriate stack slot. 1947 if (!FPDiff) return Chain; 1948 // Calculate the new stack slot for the return address. 1949 int SlotSize = Is64Bit ? 8 : 4; 1950 int NewReturnAddrFI = 1951 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false); 1952 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 1953 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT); 1954 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx, 1955 MachinePointerInfo::getFixedStack(NewReturnAddrFI), 1956 false, false, 0); 1957 return Chain; 1958} 1959 1960SDValue 1961X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee, 1962 CallingConv::ID CallConv, bool isVarArg, 1963 bool &isTailCall, 1964 const SmallVectorImpl<ISD::OutputArg> &Outs, 1965 const SmallVectorImpl<SDValue> &OutVals, 1966 const SmallVectorImpl<ISD::InputArg> &Ins, 1967 DebugLoc dl, SelectionDAG &DAG, 1968 SmallVectorImpl<SDValue> &InVals) const { 1969 MachineFunction &MF = DAG.getMachineFunction(); 1970 bool Is64Bit = Subtarget->is64Bit(); 1971 bool IsWin64 = Subtarget->isTargetWin64(); 1972 bool IsStructRet = CallIsStructReturn(Outs); 1973 bool IsSibcall = false; 1974 1975 if (isTailCall) { 1976 // Check if it's really possible to do a tail call. 1977 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1978 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(), 1979 Outs, OutVals, Ins, DAG); 1980 1981 // Sibcalls are automatically detected tailcalls which do not require 1982 // ABI changes. 1983 if (!GuaranteedTailCallOpt && isTailCall) 1984 IsSibcall = true; 1985 1986 if (isTailCall) 1987 ++NumTailCalls; 1988 } 1989 1990 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1991 "Var args not supported with calling convention fastcc or ghc"); 1992 1993 // Analyze operands of the call, assigning locations to each operand. 1994 SmallVector<CCValAssign, 16> ArgLocs; 1995 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), 1996 ArgLocs, *DAG.getContext()); 1997 1998 // Allocate shadow area for Win64 1999 if (IsWin64) { 2000 CCInfo.AllocateStack(32, 8); 2001 } 2002 2003 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2004 2005 // Get a count of how many bytes are to be pushed on the stack. 2006 unsigned NumBytes = CCInfo.getNextStackOffset(); 2007 if (IsSibcall) 2008 // This is a sibcall. The memory operands are available in caller's 2009 // own caller's stack. 2010 NumBytes = 0; 2011 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv)) 2012 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG); 2013 2014 int FPDiff = 0; 2015 if (isTailCall && !IsSibcall) { 2016 // Lower arguments at fp - stackoffset + fpdiff. 2017 unsigned NumBytesCallerPushed = 2018 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn(); 2019 FPDiff = NumBytesCallerPushed - NumBytes; 2020 2021 // Set the delta of movement of the returnaddr stackslot. 2022 // But only set if delta is greater than previous delta. 2023 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta())) 2024 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff); 2025 } 2026 2027 if (!IsSibcall) 2028 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true)); 2029 2030 SDValue RetAddrFrIdx; 2031 // Load return adress for tail calls. 2032 if (isTailCall && FPDiff) 2033 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, 2034 Is64Bit, FPDiff, dl); 2035 2036 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2037 SmallVector<SDValue, 8> MemOpChains; 2038 SDValue StackPtr; 2039 2040 // Walk the register/memloc assignments, inserting copies/loads. In the case 2041 // of tail call optimization arguments are handle later. 2042 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2043 CCValAssign &VA = ArgLocs[i]; 2044 EVT RegVT = VA.getLocVT(); 2045 SDValue Arg = OutVals[i]; 2046 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2047 bool isByVal = Flags.isByVal(); 2048 2049 // Promote the value if needed. 2050 switch (VA.getLocInfo()) { 2051 default: llvm_unreachable("Unknown loc info!"); 2052 case CCValAssign::Full: break; 2053 case CCValAssign::SExt: 2054 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg); 2055 break; 2056 case CCValAssign::ZExt: 2057 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg); 2058 break; 2059 case CCValAssign::AExt: 2060 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) { 2061 // Special case: passing MMX values in XMM registers. 2062 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 2063 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg); 2064 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg); 2065 } else 2066 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg); 2067 break; 2068 case CCValAssign::BCvt: 2069 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg); 2070 break; 2071 case CCValAssign::Indirect: { 2072 // Store the argument. 2073 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT()); 2074 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2075 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot, 2076 MachinePointerInfo::getFixedStack(FI), 2077 false, false, 0); 2078 Arg = SpillSlot; 2079 break; 2080 } 2081 } 2082 2083 if (VA.isRegLoc()) { 2084 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2085 if (isVarArg && IsWin64) { 2086 // Win64 ABI requires argument XMM reg to be copied to the corresponding 2087 // shadow reg if callee is a varargs function. 2088 unsigned ShadowReg = 0; 2089 switch (VA.getLocReg()) { 2090 case X86::XMM0: ShadowReg = X86::RCX; break; 2091 case X86::XMM1: ShadowReg = X86::RDX; break; 2092 case X86::XMM2: ShadowReg = X86::R8; break; 2093 case X86::XMM3: ShadowReg = X86::R9; break; 2094 } 2095 if (ShadowReg) 2096 RegsToPass.push_back(std::make_pair(ShadowReg, Arg)); 2097 } 2098 } else if (!IsSibcall && (!isTailCall || isByVal)) { 2099 assert(VA.isMemLoc()); 2100 if (StackPtr.getNode() == 0) 2101 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy()); 2102 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2103 dl, DAG, VA, Flags)); 2104 } 2105 } 2106 2107 if (!MemOpChains.empty()) 2108 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2109 &MemOpChains[0], MemOpChains.size()); 2110 2111 // Build a sequence of copy-to-reg nodes chained together with token chain 2112 // and flag operands which copy the outgoing args into registers. 2113 SDValue InFlag; 2114 // Tail call byval lowering might overwrite argument registers so in case of 2115 // tail call optimization the copies to registers are lowered later. 2116 if (!isTailCall) 2117 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2118 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2119 RegsToPass[i].second, InFlag); 2120 InFlag = Chain.getValue(1); 2121 } 2122 2123 if (Subtarget->isPICStyleGOT()) { 2124 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2125 // GOT pointer. 2126 if (!isTailCall) { 2127 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX, 2128 DAG.getNode(X86ISD::GlobalBaseReg, 2129 DebugLoc(), getPointerTy()), 2130 InFlag); 2131 InFlag = Chain.getValue(1); 2132 } else { 2133 // If we are tail calling and generating PIC/GOT style code load the 2134 // address of the callee into ECX. The value in ecx is used as target of 2135 // the tail jump. This is done to circumvent the ebx/callee-saved problem 2136 // for tail calls on PIC/GOT architectures. Normally we would just put the 2137 // address of GOT into ebx and then call target@PLT. But for tail calls 2138 // ebx would be restored (since ebx is callee saved) before jumping to the 2139 // target@PLT. 2140 2141 // Note: The actual moving to ECX is done further down. 2142 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 2143 if (G && !G->getGlobal()->hasHiddenVisibility() && 2144 !G->getGlobal()->hasProtectedVisibility()) 2145 Callee = LowerGlobalAddress(Callee, DAG); 2146 else if (isa<ExternalSymbolSDNode>(Callee)) 2147 Callee = LowerExternalSymbol(Callee, DAG); 2148 } 2149 } 2150 2151 if (Is64Bit && isVarArg && !IsWin64) { 2152 // From AMD64 ABI document: 2153 // For calls that may call functions that use varargs or stdargs 2154 // (prototype-less calls or calls to functions containing ellipsis (...) in 2155 // the declaration) %al is used as hidden argument to specify the number 2156 // of SSE registers used. The contents of %al do not need to match exactly 2157 // the number of registers, but must be an ubound on the number of SSE 2158 // registers used and is in the range 0 - 8 inclusive. 2159 2160 // Count the number of XMM registers allocated. 2161 static const unsigned XMMArgRegs[] = { 2162 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2163 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2164 }; 2165 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2166 assert((Subtarget->hasXMM() || !NumXMMRegs) 2167 && "SSE registers cannot be used when SSE is disabled"); 2168 2169 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, 2170 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag); 2171 InFlag = Chain.getValue(1); 2172 } 2173 2174 2175 // For tail calls lower the arguments to the 'real' stack slot. 2176 if (isTailCall) { 2177 // Force all the incoming stack arguments to be loaded from the stack 2178 // before any new outgoing arguments are stored to the stack, because the 2179 // outgoing stack slots may alias the incoming argument stack slots, and 2180 // the alias isn't otherwise explicit. This is slightly more conservative 2181 // than necessary, because it means that each store effectively depends 2182 // on every argument instead of just those arguments it would clobber. 2183 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain); 2184 2185 SmallVector<SDValue, 8> MemOpChains2; 2186 SDValue FIN; 2187 int FI = 0; 2188 // Do not flag preceeding copytoreg stuff together with the following stuff. 2189 InFlag = SDValue(); 2190 if (GuaranteedTailCallOpt) { 2191 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2192 CCValAssign &VA = ArgLocs[i]; 2193 if (VA.isRegLoc()) 2194 continue; 2195 assert(VA.isMemLoc()); 2196 SDValue Arg = OutVals[i]; 2197 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2198 // Create frame index. 2199 int32_t Offset = VA.getLocMemOffset()+FPDiff; 2200 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8; 2201 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2202 FIN = DAG.getFrameIndex(FI, getPointerTy()); 2203 2204 if (Flags.isByVal()) { 2205 // Copy relative to framepointer. 2206 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset()); 2207 if (StackPtr.getNode() == 0) 2208 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, 2209 getPointerTy()); 2210 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source); 2211 2212 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, 2213 ArgChain, 2214 Flags, DAG, dl)); 2215 } else { 2216 // Store relative to framepointer. 2217 MemOpChains2.push_back( 2218 DAG.getStore(ArgChain, dl, Arg, FIN, 2219 MachinePointerInfo::getFixedStack(FI), 2220 false, false, 0)); 2221 } 2222 } 2223 } 2224 2225 if (!MemOpChains2.empty()) 2226 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2227 &MemOpChains2[0], MemOpChains2.size()); 2228 2229 // Copy arguments to their registers. 2230 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2231 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2232 RegsToPass[i].second, InFlag); 2233 InFlag = Chain.getValue(1); 2234 } 2235 InFlag =SDValue(); 2236 2237 // Store the return address to the appropriate stack slot. 2238 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit, 2239 FPDiff, dl); 2240 } 2241 2242 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 2243 assert(Is64Bit && "Large code model is only legal in 64-bit mode."); 2244 // In the 64-bit large code model, we have to make all calls 2245 // through a register, since the call instruction's 32-bit 2246 // pc-relative offset may not be large enough to hold the whole 2247 // address. 2248 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2249 // If the callee is a GlobalAddress node (quite common, every direct call 2250 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack 2251 // it. 2252 2253 // We should use extra load for direct calls to dllimported functions in 2254 // non-JIT mode. 2255 const GlobalValue *GV = G->getGlobal(); 2256 if (!GV->hasDLLImportLinkage()) { 2257 unsigned char OpFlags = 0; 2258 2259 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2260 // external symbols most go through the PLT in PIC mode. If the symbol 2261 // has hidden or protected visibility, or if it is static or local, then 2262 // we don't need to use the PLT - we can directly call it. 2263 if (Subtarget->isTargetELF() && 2264 getTargetMachine().getRelocationModel() == Reloc::PIC_ && 2265 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2266 OpFlags = X86II::MO_PLT; 2267 } else if (Subtarget->isPICStyleStubAny() && 2268 (GV->isDeclaration() || GV->isWeakForLinker()) && 2269 Subtarget->getDarwinVers() < 9) { 2270 // PC-relative references to external symbols should go through $stub, 2271 // unless we're building with the leopard linker or later, which 2272 // automatically synthesizes these stubs. 2273 OpFlags = X86II::MO_DARWIN_STUB; 2274 } 2275 2276 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 2277 G->getOffset(), OpFlags); 2278 } 2279 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2280 unsigned char OpFlags = 0; 2281 2282 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to 2283 // external symbols should go through the PLT. 2284 if (Subtarget->isTargetELF() && 2285 getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2286 OpFlags = X86II::MO_PLT; 2287 } else if (Subtarget->isPICStyleStubAny() && 2288 Subtarget->getDarwinVers() < 9) { 2289 // PC-relative references to external symbols should go through $stub, 2290 // unless we're building with the leopard linker or later, which 2291 // automatically synthesizes these stubs. 2292 OpFlags = X86II::MO_DARWIN_STUB; 2293 } 2294 2295 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(), 2296 OpFlags); 2297 } 2298 2299 // Returns a chain & a flag for retval copy to use. 2300 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2301 SmallVector<SDValue, 8> Ops; 2302 2303 if (!IsSibcall && isTailCall) { 2304 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2305 DAG.getIntPtrConstant(0, true), InFlag); 2306 InFlag = Chain.getValue(1); 2307 } 2308 2309 Ops.push_back(Chain); 2310 Ops.push_back(Callee); 2311 2312 if (isTailCall) 2313 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32)); 2314 2315 // Add argument registers to the end of the list so that they are known live 2316 // into the call. 2317 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2318 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2319 RegsToPass[i].second.getValueType())); 2320 2321 // Add an implicit use GOT pointer in EBX. 2322 if (!isTailCall && Subtarget->isPICStyleGOT()) 2323 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy())); 2324 2325 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions. 2326 if (Is64Bit && isVarArg && !IsWin64) 2327 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8)); 2328 2329 if (InFlag.getNode()) 2330 Ops.push_back(InFlag); 2331 2332 if (isTailCall) { 2333 // We used to do: 2334 //// If this is the first return lowered for this function, add the regs 2335 //// to the liveout set for the function. 2336 // This isn't right, although it's probably harmless on x86; liveouts 2337 // should be computed from returns not tail calls. Consider a void 2338 // function making a tail call to a function returning int. 2339 return DAG.getNode(X86ISD::TC_RETURN, dl, 2340 NodeTys, &Ops[0], Ops.size()); 2341 } 2342 2343 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); 2344 InFlag = Chain.getValue(1); 2345 2346 // Create the CALLSEQ_END node. 2347 unsigned NumBytesForCalleeToPush; 2348 if (Subtarget->IsCalleePop(isVarArg, CallConv)) 2349 NumBytesForCalleeToPush = NumBytes; // Callee pops everything 2350 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet) 2351 // If this is a call to a struct-return function, the callee 2352 // pops the hidden struct pointer, so we have to push it back. 2353 // This is common for Darwin/X86, Linux & Mingw32 targets. 2354 NumBytesForCalleeToPush = 4; 2355 else 2356 NumBytesForCalleeToPush = 0; // Callee pops nothing. 2357 2358 // Returns a flag for retval copy to use. 2359 if (!IsSibcall) { 2360 Chain = DAG.getCALLSEQ_END(Chain, 2361 DAG.getIntPtrConstant(NumBytes, true), 2362 DAG.getIntPtrConstant(NumBytesForCalleeToPush, 2363 true), 2364 InFlag); 2365 InFlag = Chain.getValue(1); 2366 } 2367 2368 // Handle result values, copying them out of physregs into vregs that we 2369 // return. 2370 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2371 Ins, dl, DAG, InVals); 2372} 2373 2374 2375//===----------------------------------------------------------------------===// 2376// Fast Calling Convention (tail call) implementation 2377//===----------------------------------------------------------------------===// 2378 2379// Like std call, callee cleans arguments, convention except that ECX is 2380// reserved for storing the tail called function address. Only 2 registers are 2381// free for argument passing (inreg). Tail call optimization is performed 2382// provided: 2383// * tailcallopt is enabled 2384// * caller/callee are fastcc 2385// On X86_64 architecture with GOT-style position independent code only local 2386// (within module) calls are supported at the moment. 2387// To keep the stack aligned according to platform abi the function 2388// GetAlignedArgumentStackSize ensures that argument delta is always multiples 2389// of stack alignment. (Dynamic linkers need this - darwin's dyld for example) 2390// If a tail called function callee has more arguments than the caller the 2391// caller needs to make sure that there is room to move the RETADDR to. This is 2392// achieved by reserving an area the size of the argument delta right after the 2393// original REtADDR, but before the saved framepointer or the spilled registers 2394// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4) 2395// stack layout: 2396// arg1 2397// arg2 2398// RETADDR 2399// [ new RETADDR 2400// move area ] 2401// (possible EBP) 2402// ESI 2403// EDI 2404// local1 .. 2405 2406/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned 2407/// for a 16 byte align requirement. 2408unsigned 2409X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 2410 SelectionDAG& DAG) const { 2411 MachineFunction &MF = DAG.getMachineFunction(); 2412 const TargetMachine &TM = MF.getTarget(); 2413 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 2414 unsigned StackAlignment = TFI.getStackAlignment(); 2415 uint64_t AlignMask = StackAlignment - 1; 2416 int64_t Offset = StackSize; 2417 uint64_t SlotSize = TD->getPointerSize(); 2418 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) { 2419 // Number smaller than 12 so just add the difference. 2420 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask)); 2421 } else { 2422 // Mask out lower bits, add stackalignment once plus the 12 bytes. 2423 Offset = ((~AlignMask) & Offset) + StackAlignment + 2424 (StackAlignment-SlotSize); 2425 } 2426 return Offset; 2427} 2428 2429/// MatchingStackOffset - Return true if the given stack call argument is 2430/// already available in the same position (relatively) of the caller's 2431/// incoming argument stack. 2432static 2433bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2434 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2435 const X86InstrInfo *TII) { 2436 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2437 int FI = INT_MAX; 2438 if (Arg.getOpcode() == ISD::CopyFromReg) { 2439 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2440 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2441 return false; 2442 MachineInstr *Def = MRI->getVRegDef(VR); 2443 if (!Def) 2444 return false; 2445 if (!Flags.isByVal()) { 2446 if (!TII->isLoadFromStackSlot(Def, FI)) 2447 return false; 2448 } else { 2449 unsigned Opcode = Def->getOpcode(); 2450 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) && 2451 Def->getOperand(1).isFI()) { 2452 FI = Def->getOperand(1).getIndex(); 2453 Bytes = Flags.getByValSize(); 2454 } else 2455 return false; 2456 } 2457 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2458 if (Flags.isByVal()) 2459 // ByVal argument is passed in as a pointer but it's now being 2460 // dereferenced. e.g. 2461 // define @foo(%struct.X* %A) { 2462 // tail call @bar(%struct.X* byval %A) 2463 // } 2464 return false; 2465 SDValue Ptr = Ld->getBasePtr(); 2466 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2467 if (!FINode) 2468 return false; 2469 FI = FINode->getIndex(); 2470 } else 2471 return false; 2472 2473 assert(FI != INT_MAX); 2474 if (!MFI->isFixedObjectIndex(FI)) 2475 return false; 2476 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2477} 2478 2479/// IsEligibleForTailCallOptimization - Check whether the call is eligible 2480/// for tail call optimization. Targets which want to do tail call 2481/// optimization should implement this function. 2482bool 2483X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2484 CallingConv::ID CalleeCC, 2485 bool isVarArg, 2486 bool isCalleeStructRet, 2487 bool isCallerStructRet, 2488 const SmallVectorImpl<ISD::OutputArg> &Outs, 2489 const SmallVectorImpl<SDValue> &OutVals, 2490 const SmallVectorImpl<ISD::InputArg> &Ins, 2491 SelectionDAG& DAG) const { 2492 if (!IsTailCallConvention(CalleeCC) && 2493 CalleeCC != CallingConv::C) 2494 return false; 2495 2496 // If -tailcallopt is specified, make fastcc functions tail-callable. 2497 const MachineFunction &MF = DAG.getMachineFunction(); 2498 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2499 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2500 bool CCMatch = CallerCC == CalleeCC; 2501 2502 if (GuaranteedTailCallOpt) { 2503 if (IsTailCallConvention(CalleeCC) && CCMatch) 2504 return true; 2505 return false; 2506 } 2507 2508 // Look for obvious safe cases to perform tail call optimization that do not 2509 // require ABI changes. This is what gcc calls sibcall. 2510 2511 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to 2512 // emit a special epilogue. 2513 if (RegInfo->needsStackRealignment(MF)) 2514 return false; 2515 2516 // Do not sibcall optimize vararg calls unless the call site is not passing 2517 // any arguments. 2518 if (isVarArg && !Outs.empty()) 2519 return false; 2520 2521 // Also avoid sibcall optimization if either caller or callee uses struct 2522 // return semantics. 2523 if (isCalleeStructRet || isCallerStructRet) 2524 return false; 2525 2526 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack. 2527 // Therefore if it's not used by the call it is not safe to optimize this into 2528 // a sibcall. 2529 bool Unused = false; 2530 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 2531 if (!Ins[i].Used) { 2532 Unused = true; 2533 break; 2534 } 2535 } 2536 if (Unused) { 2537 SmallVector<CCValAssign, 16> RVLocs; 2538 CCState CCInfo(CalleeCC, false, getTargetMachine(), 2539 RVLocs, *DAG.getContext()); 2540 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 2541 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 2542 CCValAssign &VA = RVLocs[i]; 2543 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 2544 return false; 2545 } 2546 } 2547 2548 // If the calling conventions do not match, then we'd better make sure the 2549 // results are returned in the same way as what the caller expects. 2550 if (!CCMatch) { 2551 SmallVector<CCValAssign, 16> RVLocs1; 2552 CCState CCInfo1(CalleeCC, false, getTargetMachine(), 2553 RVLocs1, *DAG.getContext()); 2554 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86); 2555 2556 SmallVector<CCValAssign, 16> RVLocs2; 2557 CCState CCInfo2(CallerCC, false, getTargetMachine(), 2558 RVLocs2, *DAG.getContext()); 2559 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86); 2560 2561 if (RVLocs1.size() != RVLocs2.size()) 2562 return false; 2563 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2564 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2565 return false; 2566 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2567 return false; 2568 if (RVLocs1[i].isRegLoc()) { 2569 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2570 return false; 2571 } else { 2572 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2573 return false; 2574 } 2575 } 2576 } 2577 2578 // If the callee takes no arguments then go on to check the results of the 2579 // call. 2580 if (!Outs.empty()) { 2581 // Check if stack adjustment is needed. For now, do not do this if any 2582 // argument is passed on the stack. 2583 SmallVector<CCValAssign, 16> ArgLocs; 2584 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(), 2585 ArgLocs, *DAG.getContext()); 2586 2587 // Allocate shadow area for Win64 2588 if (Subtarget->isTargetWin64()) { 2589 CCInfo.AllocateStack(32, 8); 2590 } 2591 2592 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2593 if (CCInfo.getNextStackOffset()) { 2594 MachineFunction &MF = DAG.getMachineFunction(); 2595 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) 2596 return false; 2597 2598 // Check if the arguments are already laid out in the right way as 2599 // the caller's fixed stack objects. 2600 MachineFrameInfo *MFI = MF.getFrameInfo(); 2601 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2602 const X86InstrInfo *TII = 2603 ((X86TargetMachine&)getTargetMachine()).getInstrInfo(); 2604 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2605 CCValAssign &VA = ArgLocs[i]; 2606 SDValue Arg = OutVals[i]; 2607 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2608 if (VA.getLocInfo() == CCValAssign::Indirect) 2609 return false; 2610 if (!VA.isRegLoc()) { 2611 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2612 MFI, MRI, TII)) 2613 return false; 2614 } 2615 } 2616 } 2617 2618 // If the tailcall address may be in a register, then make sure it's 2619 // possible to register allocate for it. In 32-bit, the call address can 2620 // only target EAX, EDX, or ECX since the tail call must be scheduled after 2621 // callee-saved registers are restored. These happen to be the same 2622 // registers used to pass 'inreg' arguments so watch out for those. 2623 if (!Subtarget->is64Bit() && 2624 !isa<GlobalAddressSDNode>(Callee) && 2625 !isa<ExternalSymbolSDNode>(Callee)) { 2626 unsigned NumInRegs = 0; 2627 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2628 CCValAssign &VA = ArgLocs[i]; 2629 if (!VA.isRegLoc()) 2630 continue; 2631 unsigned Reg = VA.getLocReg(); 2632 switch (Reg) { 2633 default: break; 2634 case X86::EAX: case X86::EDX: case X86::ECX: 2635 if (++NumInRegs == 3) 2636 return false; 2637 break; 2638 } 2639 } 2640 } 2641 } 2642 2643 // An stdcall caller is expected to clean up its arguments; the callee 2644 // isn't going to do that. 2645 if (!CCMatch && CallerCC==CallingConv::X86_StdCall) 2646 return false; 2647 2648 return true; 2649} 2650 2651FastISel * 2652X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const { 2653 return X86::createFastISel(funcInfo); 2654} 2655 2656 2657//===----------------------------------------------------------------------===// 2658// Other Lowering Hooks 2659//===----------------------------------------------------------------------===// 2660 2661static bool MayFoldLoad(SDValue Op) { 2662 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode()); 2663} 2664 2665static bool MayFoldIntoStore(SDValue Op) { 2666 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin()); 2667} 2668 2669static bool isTargetShuffle(unsigned Opcode) { 2670 switch(Opcode) { 2671 default: return false; 2672 case X86ISD::PSHUFD: 2673 case X86ISD::PSHUFHW: 2674 case X86ISD::PSHUFLW: 2675 case X86ISD::SHUFPD: 2676 case X86ISD::PALIGN: 2677 case X86ISD::SHUFPS: 2678 case X86ISD::MOVLHPS: 2679 case X86ISD::MOVLHPD: 2680 case X86ISD::MOVHLPS: 2681 case X86ISD::MOVLPS: 2682 case X86ISD::MOVLPD: 2683 case X86ISD::MOVSHDUP: 2684 case X86ISD::MOVSLDUP: 2685 case X86ISD::MOVDDUP: 2686 case X86ISD::MOVSS: 2687 case X86ISD::MOVSD: 2688 case X86ISD::UNPCKLPS: 2689 case X86ISD::UNPCKLPD: 2690 case X86ISD::VUNPCKLPS: 2691 case X86ISD::VUNPCKLPD: 2692 case X86ISD::VUNPCKLPSY: 2693 case X86ISD::VUNPCKLPDY: 2694 case X86ISD::PUNPCKLWD: 2695 case X86ISD::PUNPCKLBW: 2696 case X86ISD::PUNPCKLDQ: 2697 case X86ISD::PUNPCKLQDQ: 2698 case X86ISD::UNPCKHPS: 2699 case X86ISD::UNPCKHPD: 2700 case X86ISD::PUNPCKHWD: 2701 case X86ISD::PUNPCKHBW: 2702 case X86ISD::PUNPCKHDQ: 2703 case X86ISD::PUNPCKHQDQ: 2704 return true; 2705 } 2706 return false; 2707} 2708 2709static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2710 SDValue V1, SelectionDAG &DAG) { 2711 switch(Opc) { 2712 default: llvm_unreachable("Unknown x86 shuffle node"); 2713 case X86ISD::MOVSHDUP: 2714 case X86ISD::MOVSLDUP: 2715 case X86ISD::MOVDDUP: 2716 return DAG.getNode(Opc, dl, VT, V1); 2717 } 2718 2719 return SDValue(); 2720} 2721 2722static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2723 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) { 2724 switch(Opc) { 2725 default: llvm_unreachable("Unknown x86 shuffle node"); 2726 case X86ISD::PSHUFD: 2727 case X86ISD::PSHUFHW: 2728 case X86ISD::PSHUFLW: 2729 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8)); 2730 } 2731 2732 return SDValue(); 2733} 2734 2735static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2736 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) { 2737 switch(Opc) { 2738 default: llvm_unreachable("Unknown x86 shuffle node"); 2739 case X86ISD::PALIGN: 2740 case X86ISD::SHUFPD: 2741 case X86ISD::SHUFPS: 2742 return DAG.getNode(Opc, dl, VT, V1, V2, 2743 DAG.getConstant(TargetMask, MVT::i8)); 2744 } 2745 return SDValue(); 2746} 2747 2748static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2749 SDValue V1, SDValue V2, SelectionDAG &DAG) { 2750 switch(Opc) { 2751 default: llvm_unreachable("Unknown x86 shuffle node"); 2752 case X86ISD::MOVLHPS: 2753 case X86ISD::MOVLHPD: 2754 case X86ISD::MOVHLPS: 2755 case X86ISD::MOVLPS: 2756 case X86ISD::MOVLPD: 2757 case X86ISD::MOVSS: 2758 case X86ISD::MOVSD: 2759 case X86ISD::UNPCKLPS: 2760 case X86ISD::UNPCKLPD: 2761 case X86ISD::VUNPCKLPS: 2762 case X86ISD::VUNPCKLPD: 2763 case X86ISD::VUNPCKLPSY: 2764 case X86ISD::VUNPCKLPDY: 2765 case X86ISD::PUNPCKLWD: 2766 case X86ISD::PUNPCKLBW: 2767 case X86ISD::PUNPCKLDQ: 2768 case X86ISD::PUNPCKLQDQ: 2769 case X86ISD::UNPCKHPS: 2770 case X86ISD::UNPCKHPD: 2771 case X86ISD::PUNPCKHWD: 2772 case X86ISD::PUNPCKHBW: 2773 case X86ISD::PUNPCKHDQ: 2774 case X86ISD::PUNPCKHQDQ: 2775 return DAG.getNode(Opc, dl, VT, V1, V2); 2776 } 2777 return SDValue(); 2778} 2779 2780SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { 2781 MachineFunction &MF = DAG.getMachineFunction(); 2782 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2783 int ReturnAddrIndex = FuncInfo->getRAIndex(); 2784 2785 if (ReturnAddrIndex == 0) { 2786 // Set up a frame object for the return address. 2787 uint64_t SlotSize = TD->getPointerSize(); 2788 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize, 2789 false); 2790 FuncInfo->setRAIndex(ReturnAddrIndex); 2791 } 2792 2793 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); 2794} 2795 2796 2797bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, 2798 bool hasSymbolicDisplacement) { 2799 // Offset should fit into 32 bit immediate field. 2800 if (!isInt<32>(Offset)) 2801 return false; 2802 2803 // If we don't have a symbolic displacement - we don't have any extra 2804 // restrictions. 2805 if (!hasSymbolicDisplacement) 2806 return true; 2807 2808 // FIXME: Some tweaks might be needed for medium code model. 2809 if (M != CodeModel::Small && M != CodeModel::Kernel) 2810 return false; 2811 2812 // For small code model we assume that latest object is 16MB before end of 31 2813 // bits boundary. We may also accept pretty large negative constants knowing 2814 // that all objects are in the positive half of address space. 2815 if (M == CodeModel::Small && Offset < 16*1024*1024) 2816 return true; 2817 2818 // For kernel code model we know that all object resist in the negative half 2819 // of 32bits address space. We may not accept negative offsets, since they may 2820 // be just off and we may accept pretty large positive ones. 2821 if (M == CodeModel::Kernel && Offset > 0) 2822 return true; 2823 2824 return false; 2825} 2826 2827/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86 2828/// specific condition code, returning the condition code and the LHS/RHS of the 2829/// comparison to make. 2830static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP, 2831 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) { 2832 if (!isFP) { 2833 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 2834 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) { 2835 // X > -1 -> X == 0, jump !sign. 2836 RHS = DAG.getConstant(0, RHS.getValueType()); 2837 return X86::COND_NS; 2838 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) { 2839 // X < 0 -> X == 0, jump on sign. 2840 return X86::COND_S; 2841 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) { 2842 // X < 1 -> X <= 0 2843 RHS = DAG.getConstant(0, RHS.getValueType()); 2844 return X86::COND_LE; 2845 } 2846 } 2847 2848 switch (SetCCOpcode) { 2849 default: llvm_unreachable("Invalid integer condition!"); 2850 case ISD::SETEQ: return X86::COND_E; 2851 case ISD::SETGT: return X86::COND_G; 2852 case ISD::SETGE: return X86::COND_GE; 2853 case ISD::SETLT: return X86::COND_L; 2854 case ISD::SETLE: return X86::COND_LE; 2855 case ISD::SETNE: return X86::COND_NE; 2856 case ISD::SETULT: return X86::COND_B; 2857 case ISD::SETUGT: return X86::COND_A; 2858 case ISD::SETULE: return X86::COND_BE; 2859 case ISD::SETUGE: return X86::COND_AE; 2860 } 2861 } 2862 2863 // First determine if it is required or is profitable to flip the operands. 2864 2865 // If LHS is a foldable load, but RHS is not, flip the condition. 2866 if (ISD::isNON_EXTLoad(LHS.getNode()) && 2867 !ISD::isNON_EXTLoad(RHS.getNode())) { 2868 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode); 2869 std::swap(LHS, RHS); 2870 } 2871 2872 switch (SetCCOpcode) { 2873 default: break; 2874 case ISD::SETOLT: 2875 case ISD::SETOLE: 2876 case ISD::SETUGT: 2877 case ISD::SETUGE: 2878 std::swap(LHS, RHS); 2879 break; 2880 } 2881 2882 // On a floating point condition, the flags are set as follows: 2883 // ZF PF CF op 2884 // 0 | 0 | 0 | X > Y 2885 // 0 | 0 | 1 | X < Y 2886 // 1 | 0 | 0 | X == Y 2887 // 1 | 1 | 1 | unordered 2888 switch (SetCCOpcode) { 2889 default: llvm_unreachable("Condcode should be pre-legalized away"); 2890 case ISD::SETUEQ: 2891 case ISD::SETEQ: return X86::COND_E; 2892 case ISD::SETOLT: // flipped 2893 case ISD::SETOGT: 2894 case ISD::SETGT: return X86::COND_A; 2895 case ISD::SETOLE: // flipped 2896 case ISD::SETOGE: 2897 case ISD::SETGE: return X86::COND_AE; 2898 case ISD::SETUGT: // flipped 2899 case ISD::SETULT: 2900 case ISD::SETLT: return X86::COND_B; 2901 case ISD::SETUGE: // flipped 2902 case ISD::SETULE: 2903 case ISD::SETLE: return X86::COND_BE; 2904 case ISD::SETONE: 2905 case ISD::SETNE: return X86::COND_NE; 2906 case ISD::SETUO: return X86::COND_P; 2907 case ISD::SETO: return X86::COND_NP; 2908 case ISD::SETOEQ: 2909 case ISD::SETUNE: return X86::COND_INVALID; 2910 } 2911} 2912 2913/// hasFPCMov - is there a floating point cmov for the specific X86 condition 2914/// code. Current x86 isa includes the following FP cmov instructions: 2915/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu. 2916static bool hasFPCMov(unsigned X86CC) { 2917 switch (X86CC) { 2918 default: 2919 return false; 2920 case X86::COND_B: 2921 case X86::COND_BE: 2922 case X86::COND_E: 2923 case X86::COND_P: 2924 case X86::COND_A: 2925 case X86::COND_AE: 2926 case X86::COND_NE: 2927 case X86::COND_NP: 2928 return true; 2929 } 2930} 2931 2932/// isFPImmLegal - Returns true if the target can instruction select the 2933/// specified FP immediate natively. If false, the legalizer will 2934/// materialize the FP immediate as a load from a constant pool. 2935bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 2936 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) { 2937 if (Imm.bitwiseIsEqual(LegalFPImmediates[i])) 2938 return true; 2939 } 2940 return false; 2941} 2942 2943/// isUndefOrInRange - Return true if Val is undef or if its value falls within 2944/// the specified range (L, H]. 2945static bool isUndefOrInRange(int Val, int Low, int Hi) { 2946 return (Val < 0) || (Val >= Low && Val < Hi); 2947} 2948 2949/// isUndefOrEqual - Val is either less than zero (undef) or equal to the 2950/// specified value. 2951static bool isUndefOrEqual(int Val, int CmpVal) { 2952 if (Val < 0 || Val == CmpVal) 2953 return true; 2954 return false; 2955} 2956 2957/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that 2958/// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference 2959/// the second operand. 2960static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) { 2961 if (VT == MVT::v4f32 || VT == MVT::v4i32 ) 2962 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4); 2963 if (VT == MVT::v2f64 || VT == MVT::v2i64) 2964 return (Mask[0] < 2 && Mask[1] < 2); 2965 return false; 2966} 2967 2968bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) { 2969 SmallVector<int, 8> M; 2970 N->getMask(M); 2971 return ::isPSHUFDMask(M, N->getValueType(0)); 2972} 2973 2974/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that 2975/// is suitable for input to PSHUFHW. 2976static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 2977 if (VT != MVT::v8i16) 2978 return false; 2979 2980 // Lower quadword copied in order or undef. 2981 for (int i = 0; i != 4; ++i) 2982 if (Mask[i] >= 0 && Mask[i] != i) 2983 return false; 2984 2985 // Upper quadword shuffled. 2986 for (int i = 4; i != 8; ++i) 2987 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7)) 2988 return false; 2989 2990 return true; 2991} 2992 2993bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) { 2994 SmallVector<int, 8> M; 2995 N->getMask(M); 2996 return ::isPSHUFHWMask(M, N->getValueType(0)); 2997} 2998 2999/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that 3000/// is suitable for input to PSHUFLW. 3001static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3002 if (VT != MVT::v8i16) 3003 return false; 3004 3005 // Upper quadword copied in order. 3006 for (int i = 4; i != 8; ++i) 3007 if (Mask[i] >= 0 && Mask[i] != i) 3008 return false; 3009 3010 // Lower quadword shuffled. 3011 for (int i = 0; i != 4; ++i) 3012 if (Mask[i] >= 4) 3013 return false; 3014 3015 return true; 3016} 3017 3018bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) { 3019 SmallVector<int, 8> M; 3020 N->getMask(M); 3021 return ::isPSHUFLWMask(M, N->getValueType(0)); 3022} 3023 3024/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that 3025/// is suitable for input to PALIGNR. 3026static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT, 3027 bool hasSSSE3) { 3028 int i, e = VT.getVectorNumElements(); 3029 3030 // Do not handle v2i64 / v2f64 shuffles with palignr. 3031 if (e < 4 || !hasSSSE3) 3032 return false; 3033 3034 for (i = 0; i != e; ++i) 3035 if (Mask[i] >= 0) 3036 break; 3037 3038 // All undef, not a palignr. 3039 if (i == e) 3040 return false; 3041 3042 // Determine if it's ok to perform a palignr with only the LHS, since we 3043 // don't have access to the actual shuffle elements to see if RHS is undef. 3044 bool Unary = Mask[i] < (int)e; 3045 bool NeedsUnary = false; 3046 3047 int s = Mask[i] - i; 3048 3049 // Check the rest of the elements to see if they are consecutive. 3050 for (++i; i != e; ++i) { 3051 int m = Mask[i]; 3052 if (m < 0) 3053 continue; 3054 3055 Unary = Unary && (m < (int)e); 3056 NeedsUnary = NeedsUnary || (m < s); 3057 3058 if (NeedsUnary && !Unary) 3059 return false; 3060 if (Unary && m != ((s+i) & (e-1))) 3061 return false; 3062 if (!Unary && m != (s+i)) 3063 return false; 3064 } 3065 return true; 3066} 3067 3068bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) { 3069 SmallVector<int, 8> M; 3070 N->getMask(M); 3071 return ::isPALIGNRMask(M, N->getValueType(0), true); 3072} 3073 3074/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand 3075/// specifies a shuffle of elements that is suitable for input to SHUFP*. 3076static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3077 int NumElems = VT.getVectorNumElements(); 3078 if (NumElems != 2 && NumElems != 4) 3079 return false; 3080 3081 int Half = NumElems / 2; 3082 for (int i = 0; i < Half; ++i) 3083 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3084 return false; 3085 for (int i = Half; i < NumElems; ++i) 3086 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3087 return false; 3088 3089 return true; 3090} 3091 3092bool X86::isSHUFPMask(ShuffleVectorSDNode *N) { 3093 SmallVector<int, 8> M; 3094 N->getMask(M); 3095 return ::isSHUFPMask(M, N->getValueType(0)); 3096} 3097 3098/// isCommutedSHUFP - Returns true if the shuffle mask is exactly 3099/// the reverse of what x86 shuffles want. x86 shuffles requires the lower 3100/// half elements to come from vector 1 (which would equal the dest.) and 3101/// the upper half to come from vector 2. 3102static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3103 int NumElems = VT.getVectorNumElements(); 3104 3105 if (NumElems != 2 && NumElems != 4) 3106 return false; 3107 3108 int Half = NumElems / 2; 3109 for (int i = 0; i < Half; ++i) 3110 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3111 return false; 3112 for (int i = Half; i < NumElems; ++i) 3113 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3114 return false; 3115 return true; 3116} 3117 3118static bool isCommutedSHUFP(ShuffleVectorSDNode *N) { 3119 SmallVector<int, 8> M; 3120 N->getMask(M); 3121 return isCommutedSHUFPMask(M, N->getValueType(0)); 3122} 3123 3124/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand 3125/// specifies a shuffle of elements that is suitable for input to MOVHLPS. 3126bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) { 3127 if (N->getValueType(0).getVectorNumElements() != 4) 3128 return false; 3129 3130 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3 3131 return isUndefOrEqual(N->getMaskElt(0), 6) && 3132 isUndefOrEqual(N->getMaskElt(1), 7) && 3133 isUndefOrEqual(N->getMaskElt(2), 2) && 3134 isUndefOrEqual(N->getMaskElt(3), 3); 3135} 3136 3137/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form 3138/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef, 3139/// <2, 3, 2, 3> 3140bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) { 3141 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3142 3143 if (NumElems != 4) 3144 return false; 3145 3146 return isUndefOrEqual(N->getMaskElt(0), 2) && 3147 isUndefOrEqual(N->getMaskElt(1), 3) && 3148 isUndefOrEqual(N->getMaskElt(2), 2) && 3149 isUndefOrEqual(N->getMaskElt(3), 3); 3150} 3151 3152/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand 3153/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}. 3154bool X86::isMOVLPMask(ShuffleVectorSDNode *N) { 3155 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3156 3157 if (NumElems != 2 && NumElems != 4) 3158 return false; 3159 3160 for (unsigned i = 0; i < NumElems/2; ++i) 3161 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems)) 3162 return false; 3163 3164 for (unsigned i = NumElems/2; i < NumElems; ++i) 3165 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3166 return false; 3167 3168 return true; 3169} 3170 3171/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand 3172/// specifies a shuffle of elements that is suitable for input to MOVLHPS. 3173bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) { 3174 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3175 3176 if (NumElems != 2 && NumElems != 4) 3177 return false; 3178 3179 for (unsigned i = 0; i < NumElems/2; ++i) 3180 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3181 return false; 3182 3183 for (unsigned i = 0; i < NumElems/2; ++i) 3184 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems)) 3185 return false; 3186 3187 return true; 3188} 3189 3190/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand 3191/// specifies a shuffle of elements that is suitable for input to UNPCKL. 3192static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3193 bool V2IsSplat = false) { 3194 int NumElts = VT.getVectorNumElements(); 3195 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16) 3196 return false; 3197 3198 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) { 3199 int BitI = Mask[i]; 3200 int BitI1 = Mask[i+1]; 3201 if (!isUndefOrEqual(BitI, j)) 3202 return false; 3203 if (V2IsSplat) { 3204 if (!isUndefOrEqual(BitI1, NumElts)) 3205 return false; 3206 } else { 3207 if (!isUndefOrEqual(BitI1, j + NumElts)) 3208 return false; 3209 } 3210 } 3211 return true; 3212} 3213 3214bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) { 3215 SmallVector<int, 8> M; 3216 N->getMask(M); 3217 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat); 3218} 3219 3220/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand 3221/// specifies a shuffle of elements that is suitable for input to UNPCKH. 3222static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT, 3223 bool V2IsSplat = false) { 3224 int NumElts = VT.getVectorNumElements(); 3225 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16) 3226 return false; 3227 3228 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) { 3229 int BitI = Mask[i]; 3230 int BitI1 = Mask[i+1]; 3231 if (!isUndefOrEqual(BitI, j + NumElts/2)) 3232 return false; 3233 if (V2IsSplat) { 3234 if (isUndefOrEqual(BitI1, NumElts)) 3235 return false; 3236 } else { 3237 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts)) 3238 return false; 3239 } 3240 } 3241 return true; 3242} 3243 3244bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) { 3245 SmallVector<int, 8> M; 3246 N->getMask(M); 3247 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat); 3248} 3249 3250/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form 3251/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef, 3252/// <0, 0, 1, 1> 3253static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3254 int NumElems = VT.getVectorNumElements(); 3255 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3256 return false; 3257 3258 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) { 3259 int BitI = Mask[i]; 3260 int BitI1 = Mask[i+1]; 3261 if (!isUndefOrEqual(BitI, j)) 3262 return false; 3263 if (!isUndefOrEqual(BitI1, j)) 3264 return false; 3265 } 3266 return true; 3267} 3268 3269bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) { 3270 SmallVector<int, 8> M; 3271 N->getMask(M); 3272 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0)); 3273} 3274 3275/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form 3276/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef, 3277/// <2, 2, 3, 3> 3278static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3279 int NumElems = VT.getVectorNumElements(); 3280 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3281 return false; 3282 3283 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) { 3284 int BitI = Mask[i]; 3285 int BitI1 = Mask[i+1]; 3286 if (!isUndefOrEqual(BitI, j)) 3287 return false; 3288 if (!isUndefOrEqual(BitI1, j)) 3289 return false; 3290 } 3291 return true; 3292} 3293 3294bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) { 3295 SmallVector<int, 8> M; 3296 N->getMask(M); 3297 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0)); 3298} 3299 3300/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand 3301/// specifies a shuffle of elements that is suitable for input to MOVSS, 3302/// MOVSD, and MOVD, i.e. setting the lowest element. 3303static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3304 if (VT.getVectorElementType().getSizeInBits() < 32) 3305 return false; 3306 3307 int NumElts = VT.getVectorNumElements(); 3308 3309 if (!isUndefOrEqual(Mask[0], NumElts)) 3310 return false; 3311 3312 for (int i = 1; i < NumElts; ++i) 3313 if (!isUndefOrEqual(Mask[i], i)) 3314 return false; 3315 3316 return true; 3317} 3318 3319bool X86::isMOVLMask(ShuffleVectorSDNode *N) { 3320 SmallVector<int, 8> M; 3321 N->getMask(M); 3322 return ::isMOVLMask(M, N->getValueType(0)); 3323} 3324 3325/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse 3326/// of what x86 movss want. X86 movs requires the lowest element to be lowest 3327/// element of vector 2 and the other elements to come from vector 1 in order. 3328static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3329 bool V2IsSplat = false, bool V2IsUndef = false) { 3330 int NumOps = VT.getVectorNumElements(); 3331 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16) 3332 return false; 3333 3334 if (!isUndefOrEqual(Mask[0], 0)) 3335 return false; 3336 3337 for (int i = 1; i < NumOps; ++i) 3338 if (!(isUndefOrEqual(Mask[i], i+NumOps) || 3339 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) || 3340 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps)))) 3341 return false; 3342 3343 return true; 3344} 3345 3346static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false, 3347 bool V2IsUndef = false) { 3348 SmallVector<int, 8> M; 3349 N->getMask(M); 3350 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef); 3351} 3352 3353/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3354/// specifies a shuffle of elements that is suitable for input to MOVSHDUP. 3355bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) { 3356 if (N->getValueType(0).getVectorNumElements() != 4) 3357 return false; 3358 3359 // Expect 1, 1, 3, 3 3360 for (unsigned i = 0; i < 2; ++i) { 3361 int Elt = N->getMaskElt(i); 3362 if (Elt >= 0 && Elt != 1) 3363 return false; 3364 } 3365 3366 bool HasHi = false; 3367 for (unsigned i = 2; i < 4; ++i) { 3368 int Elt = N->getMaskElt(i); 3369 if (Elt >= 0 && Elt != 3) 3370 return false; 3371 if (Elt == 3) 3372 HasHi = true; 3373 } 3374 // Don't use movshdup if it can be done with a shufps. 3375 // FIXME: verify that matching u, u, 3, 3 is what we want. 3376 return HasHi; 3377} 3378 3379/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3380/// specifies a shuffle of elements that is suitable for input to MOVSLDUP. 3381bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) { 3382 if (N->getValueType(0).getVectorNumElements() != 4) 3383 return false; 3384 3385 // Expect 0, 0, 2, 2 3386 for (unsigned i = 0; i < 2; ++i) 3387 if (N->getMaskElt(i) > 0) 3388 return false; 3389 3390 bool HasHi = false; 3391 for (unsigned i = 2; i < 4; ++i) { 3392 int Elt = N->getMaskElt(i); 3393 if (Elt >= 0 && Elt != 2) 3394 return false; 3395 if (Elt == 2) 3396 HasHi = true; 3397 } 3398 // Don't use movsldup if it can be done with a shufps. 3399 return HasHi; 3400} 3401 3402/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3403/// specifies a shuffle of elements that is suitable for input to MOVDDUP. 3404bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) { 3405 int e = N->getValueType(0).getVectorNumElements() / 2; 3406 3407 for (int i = 0; i < e; ++i) 3408 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3409 return false; 3410 for (int i = 0; i < e; ++i) 3411 if (!isUndefOrEqual(N->getMaskElt(e+i), i)) 3412 return false; 3413 return true; 3414} 3415 3416/// isVEXTRACTF128Index - Return true if the specified 3417/// EXTRACT_SUBVECTOR operand specifies a vector extract that is 3418/// suitable for input to VEXTRACTF128. 3419bool X86::isVEXTRACTF128Index(SDNode *N) { 3420 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 3421 return false; 3422 3423 // The index should be aligned on a 128-bit boundary. 3424 uint64_t Index = 3425 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 3426 3427 unsigned VL = N->getValueType(0).getVectorNumElements(); 3428 unsigned VBits = N->getValueType(0).getSizeInBits(); 3429 unsigned ElSize = VBits / VL; 3430 bool Result = (Index * ElSize) % 128 == 0; 3431 3432 return Result; 3433} 3434 3435/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR 3436/// operand specifies a subvector insert that is suitable for input to 3437/// VINSERTF128. 3438bool X86::isVINSERTF128Index(SDNode *N) { 3439 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 3440 return false; 3441 3442 // The index should be aligned on a 128-bit boundary. 3443 uint64_t Index = 3444 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 3445 3446 unsigned VL = N->getValueType(0).getVectorNumElements(); 3447 unsigned VBits = N->getValueType(0).getSizeInBits(); 3448 unsigned ElSize = VBits / VL; 3449 bool Result = (Index * ElSize) % 128 == 0; 3450 3451 return Result; 3452} 3453 3454/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle 3455/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions. 3456unsigned X86::getShuffleSHUFImmediate(SDNode *N) { 3457 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3458 int NumOperands = SVOp->getValueType(0).getVectorNumElements(); 3459 3460 unsigned Shift = (NumOperands == 4) ? 2 : 1; 3461 unsigned Mask = 0; 3462 for (int i = 0; i < NumOperands; ++i) { 3463 int Val = SVOp->getMaskElt(NumOperands-i-1); 3464 if (Val < 0) Val = 0; 3465 if (Val >= NumOperands) Val -= NumOperands; 3466 Mask |= Val; 3467 if (i != NumOperands - 1) 3468 Mask <<= Shift; 3469 } 3470 return Mask; 3471} 3472 3473/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle 3474/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction. 3475unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) { 3476 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3477 unsigned Mask = 0; 3478 // 8 nodes, but we only care about the last 4. 3479 for (unsigned i = 7; i >= 4; --i) { 3480 int Val = SVOp->getMaskElt(i); 3481 if (Val >= 0) 3482 Mask |= (Val - 4); 3483 if (i != 4) 3484 Mask <<= 2; 3485 } 3486 return Mask; 3487} 3488 3489/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle 3490/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction. 3491unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) { 3492 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3493 unsigned Mask = 0; 3494 // 8 nodes, but we only care about the first 4. 3495 for (int i = 3; i >= 0; --i) { 3496 int Val = SVOp->getMaskElt(i); 3497 if (Val >= 0) 3498 Mask |= Val; 3499 if (i != 0) 3500 Mask <<= 2; 3501 } 3502 return Mask; 3503} 3504 3505/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle 3506/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction. 3507unsigned X86::getShufflePALIGNRImmediate(SDNode *N) { 3508 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3509 EVT VVT = N->getValueType(0); 3510 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3; 3511 int Val = 0; 3512 3513 unsigned i, e; 3514 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) { 3515 Val = SVOp->getMaskElt(i); 3516 if (Val >= 0) 3517 break; 3518 } 3519 return (Val - i) * EltSize; 3520} 3521 3522/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate 3523/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128 3524/// instructions. 3525unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) { 3526 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 3527 llvm_unreachable("Illegal extract subvector for VEXTRACTF128"); 3528 3529 uint64_t Index = 3530 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 3531 3532 EVT VecVT = N->getOperand(0).getValueType(); 3533 EVT ElVT = VecVT.getVectorElementType(); 3534 3535 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 3536 3537 return Index / NumElemsPerChunk; 3538} 3539 3540/// getInsertVINSERTF128Immediate - Return the appropriate immediate 3541/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128 3542/// instructions. 3543unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) { 3544 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 3545 llvm_unreachable("Illegal insert subvector for VINSERTF128"); 3546 3547 uint64_t Index = 3548 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 3549 3550 EVT VecVT = N->getValueType(0); 3551 EVT ElVT = VecVT.getVectorElementType(); 3552 3553 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 3554 3555 return Index / NumElemsPerChunk; 3556} 3557 3558/// isZeroNode - Returns true if Elt is a constant zero or a floating point 3559/// constant +0.0. 3560bool X86::isZeroNode(SDValue Elt) { 3561 return ((isa<ConstantSDNode>(Elt) && 3562 cast<ConstantSDNode>(Elt)->isNullValue()) || 3563 (isa<ConstantFPSDNode>(Elt) && 3564 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero())); 3565} 3566 3567/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in 3568/// their permute mask. 3569static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp, 3570 SelectionDAG &DAG) { 3571 EVT VT = SVOp->getValueType(0); 3572 unsigned NumElems = VT.getVectorNumElements(); 3573 SmallVector<int, 8> MaskVec; 3574 3575 for (unsigned i = 0; i != NumElems; ++i) { 3576 int idx = SVOp->getMaskElt(i); 3577 if (idx < 0) 3578 MaskVec.push_back(idx); 3579 else if (idx < (int)NumElems) 3580 MaskVec.push_back(idx + NumElems); 3581 else 3582 MaskVec.push_back(idx - NumElems); 3583 } 3584 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1), 3585 SVOp->getOperand(0), &MaskVec[0]); 3586} 3587 3588/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming 3589/// the two vector operands have swapped position. 3590static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) { 3591 unsigned NumElems = VT.getVectorNumElements(); 3592 for (unsigned i = 0; i != NumElems; ++i) { 3593 int idx = Mask[i]; 3594 if (idx < 0) 3595 continue; 3596 else if (idx < (int)NumElems) 3597 Mask[i] = idx + NumElems; 3598 else 3599 Mask[i] = idx - NumElems; 3600 } 3601} 3602 3603/// ShouldXformToMOVHLPS - Return true if the node should be transformed to 3604/// match movhlps. The lower half elements should come from upper half of 3605/// V1 (and in order), and the upper half elements should come from the upper 3606/// half of V2 (and in order). 3607static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) { 3608 if (Op->getValueType(0).getVectorNumElements() != 4) 3609 return false; 3610 for (unsigned i = 0, e = 2; i != e; ++i) 3611 if (!isUndefOrEqual(Op->getMaskElt(i), i+2)) 3612 return false; 3613 for (unsigned i = 2; i != 4; ++i) 3614 if (!isUndefOrEqual(Op->getMaskElt(i), i+4)) 3615 return false; 3616 return true; 3617} 3618 3619/// isScalarLoadToVector - Returns true if the node is a scalar load that 3620/// is promoted to a vector. It also returns the LoadSDNode by reference if 3621/// required. 3622static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) { 3623 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR) 3624 return false; 3625 N = N->getOperand(0).getNode(); 3626 if (!ISD::isNON_EXTLoad(N)) 3627 return false; 3628 if (LD) 3629 *LD = cast<LoadSDNode>(N); 3630 return true; 3631} 3632 3633/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to 3634/// match movlp{s|d}. The lower half elements should come from lower half of 3635/// V1 (and in order), and the upper half elements should come from the upper 3636/// half of V2 (and in order). And since V1 will become the source of the 3637/// MOVLP, it must be either a vector load or a scalar load to vector. 3638static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, 3639 ShuffleVectorSDNode *Op) { 3640 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1)) 3641 return false; 3642 // Is V2 is a vector load, don't do this transformation. We will try to use 3643 // load folding shufps op. 3644 if (ISD::isNON_EXTLoad(V2)) 3645 return false; 3646 3647 unsigned NumElems = Op->getValueType(0).getVectorNumElements(); 3648 3649 if (NumElems != 2 && NumElems != 4) 3650 return false; 3651 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3652 if (!isUndefOrEqual(Op->getMaskElt(i), i)) 3653 return false; 3654 for (unsigned i = NumElems/2; i != NumElems; ++i) 3655 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems)) 3656 return false; 3657 return true; 3658} 3659 3660/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 3661/// all the same. 3662static bool isSplatVector(SDNode *N) { 3663 if (N->getOpcode() != ISD::BUILD_VECTOR) 3664 return false; 3665 3666 SDValue SplatValue = N->getOperand(0); 3667 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i) 3668 if (N->getOperand(i) != SplatValue) 3669 return false; 3670 return true; 3671} 3672 3673/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved 3674/// to an zero vector. 3675/// FIXME: move to dag combiner / method on ShuffleVectorSDNode 3676static bool isZeroShuffle(ShuffleVectorSDNode *N) { 3677 SDValue V1 = N->getOperand(0); 3678 SDValue V2 = N->getOperand(1); 3679 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3680 for (unsigned i = 0; i != NumElems; ++i) { 3681 int Idx = N->getMaskElt(i); 3682 if (Idx >= (int)NumElems) { 3683 unsigned Opc = V2.getOpcode(); 3684 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode())) 3685 continue; 3686 if (Opc != ISD::BUILD_VECTOR || 3687 !X86::isZeroNode(V2.getOperand(Idx-NumElems))) 3688 return false; 3689 } else if (Idx >= 0) { 3690 unsigned Opc = V1.getOpcode(); 3691 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode())) 3692 continue; 3693 if (Opc != ISD::BUILD_VECTOR || 3694 !X86::isZeroNode(V1.getOperand(Idx))) 3695 return false; 3696 } 3697 } 3698 return true; 3699} 3700 3701/// getZeroVector - Returns a vector of specified type with all zero elements. 3702/// 3703static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG, 3704 DebugLoc dl) { 3705 assert(VT.isVector() && "Expected a vector type"); 3706 3707 // Always build SSE zero vectors as <4 x i32> bitcasted 3708 // to their dest type. This ensures they get CSE'd. 3709 SDValue Vec; 3710 if (VT.getSizeInBits() == 128) { // SSE 3711 if (HasSSE2) { // SSE2 3712 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 3713 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 3714 } else { // SSE1 3715 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 3716 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst); 3717 } 3718 } else if (VT.getSizeInBits() == 256) { // AVX 3719 // 256-bit logic and arithmetic instructions in AVX are 3720 // all floating-point, no support for integer ops. Default 3721 // to emitting fp zeroed vectors then. 3722 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 3723 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 3724 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8); 3725 } 3726 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 3727} 3728 3729/// getOnesVector - Returns a vector of specified type with all bits set. 3730/// 3731static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) { 3732 assert(VT.isVector() && "Expected a vector type"); 3733 3734 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest 3735 // type. This ensures they get CSE'd. 3736 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32); 3737 SDValue Vec; 3738 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 3739 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 3740} 3741 3742 3743/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements 3744/// that point to V2 points to its first element. 3745static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 3746 EVT VT = SVOp->getValueType(0); 3747 unsigned NumElems = VT.getVectorNumElements(); 3748 3749 bool Changed = false; 3750 SmallVector<int, 8> MaskVec; 3751 SVOp->getMask(MaskVec); 3752 3753 for (unsigned i = 0; i != NumElems; ++i) { 3754 if (MaskVec[i] > (int)NumElems) { 3755 MaskVec[i] = NumElems; 3756 Changed = true; 3757 } 3758 } 3759 if (Changed) 3760 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0), 3761 SVOp->getOperand(1), &MaskVec[0]); 3762 return SDValue(SVOp, 0); 3763} 3764 3765/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd 3766/// operation of specified width. 3767static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 3768 SDValue V2) { 3769 unsigned NumElems = VT.getVectorNumElements(); 3770 SmallVector<int, 8> Mask; 3771 Mask.push_back(NumElems); 3772 for (unsigned i = 1; i != NumElems; ++i) 3773 Mask.push_back(i); 3774 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 3775} 3776 3777/// getUnpackl - Returns a vector_shuffle node for an unpackl operation. 3778static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 3779 SDValue V2) { 3780 unsigned NumElems = VT.getVectorNumElements(); 3781 SmallVector<int, 8> Mask; 3782 for (unsigned i = 0, e = NumElems/2; i != e; ++i) { 3783 Mask.push_back(i); 3784 Mask.push_back(i + NumElems); 3785 } 3786 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 3787} 3788 3789/// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation. 3790static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 3791 SDValue V2) { 3792 unsigned NumElems = VT.getVectorNumElements(); 3793 unsigned Half = NumElems/2; 3794 SmallVector<int, 8> Mask; 3795 for (unsigned i = 0; i != Half; ++i) { 3796 Mask.push_back(i + Half); 3797 Mask.push_back(i + NumElems + Half); 3798 } 3799 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 3800} 3801 3802/// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32. 3803static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) { 3804 EVT PVT = MVT::v4f32; 3805 EVT VT = SV->getValueType(0); 3806 DebugLoc dl = SV->getDebugLoc(); 3807 SDValue V1 = SV->getOperand(0); 3808 int NumElems = VT.getVectorNumElements(); 3809 int EltNo = SV->getSplatIndex(); 3810 3811 // unpack elements to the correct location 3812 while (NumElems > 4) { 3813 if (EltNo < NumElems/2) { 3814 V1 = getUnpackl(DAG, dl, VT, V1, V1); 3815 } else { 3816 V1 = getUnpackh(DAG, dl, VT, V1, V1); 3817 EltNo -= NumElems/2; 3818 } 3819 NumElems >>= 1; 3820 } 3821 3822 // Perform the splat. 3823 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo }; 3824 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1); 3825 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]); 3826 return DAG.getNode(ISD::BITCAST, dl, VT, V1); 3827} 3828 3829/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified 3830/// vector of zero or undef vector. This produces a shuffle where the low 3831/// element of V2 is swizzled into the zero/undef vector, landing at element 3832/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3). 3833static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx, 3834 bool isZero, bool HasSSE2, 3835 SelectionDAG &DAG) { 3836 EVT VT = V2.getValueType(); 3837 SDValue V1 = isZero 3838 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT); 3839 unsigned NumElems = VT.getVectorNumElements(); 3840 SmallVector<int, 16> MaskVec; 3841 for (unsigned i = 0; i != NumElems; ++i) 3842 // If this is the insertion idx, put the low elt of V2 here. 3843 MaskVec.push_back(i == Idx ? NumElems : i); 3844 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]); 3845} 3846 3847/// getShuffleScalarElt - Returns the scalar element that will make up the ith 3848/// element of the result of the vector shuffle. 3849SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG, 3850 unsigned Depth) { 3851 if (Depth == 6) 3852 return SDValue(); // Limit search depth. 3853 3854 SDValue V = SDValue(N, 0); 3855 EVT VT = V.getValueType(); 3856 unsigned Opcode = V.getOpcode(); 3857 3858 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars. 3859 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) { 3860 Index = SV->getMaskElt(Index); 3861 3862 if (Index < 0) 3863 return DAG.getUNDEF(VT.getVectorElementType()); 3864 3865 int NumElems = VT.getVectorNumElements(); 3866 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1); 3867 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1); 3868 } 3869 3870 // Recurse into target specific vector shuffles to find scalars. 3871 if (isTargetShuffle(Opcode)) { 3872 int NumElems = VT.getVectorNumElements(); 3873 SmallVector<unsigned, 16> ShuffleMask; 3874 SDValue ImmN; 3875 3876 switch(Opcode) { 3877 case X86ISD::SHUFPS: 3878 case X86ISD::SHUFPD: 3879 ImmN = N->getOperand(N->getNumOperands()-1); 3880 DecodeSHUFPSMask(NumElems, 3881 cast<ConstantSDNode>(ImmN)->getZExtValue(), 3882 ShuffleMask); 3883 break; 3884 case X86ISD::PUNPCKHBW: 3885 case X86ISD::PUNPCKHWD: 3886 case X86ISD::PUNPCKHDQ: 3887 case X86ISD::PUNPCKHQDQ: 3888 DecodePUNPCKHMask(NumElems, ShuffleMask); 3889 break; 3890 case X86ISD::UNPCKHPS: 3891 case X86ISD::UNPCKHPD: 3892 DecodeUNPCKHPMask(NumElems, ShuffleMask); 3893 break; 3894 case X86ISD::PUNPCKLBW: 3895 case X86ISD::PUNPCKLWD: 3896 case X86ISD::PUNPCKLDQ: 3897 case X86ISD::PUNPCKLQDQ: 3898 DecodePUNPCKLMask(VT, ShuffleMask); 3899 break; 3900 case X86ISD::UNPCKLPS: 3901 case X86ISD::UNPCKLPD: 3902 case X86ISD::VUNPCKLPS: 3903 case X86ISD::VUNPCKLPD: 3904 case X86ISD::VUNPCKLPSY: 3905 case X86ISD::VUNPCKLPDY: 3906 DecodeUNPCKLPMask(VT, ShuffleMask); 3907 break; 3908 case X86ISD::MOVHLPS: 3909 DecodeMOVHLPSMask(NumElems, ShuffleMask); 3910 break; 3911 case X86ISD::MOVLHPS: 3912 DecodeMOVLHPSMask(NumElems, ShuffleMask); 3913 break; 3914 case X86ISD::PSHUFD: 3915 ImmN = N->getOperand(N->getNumOperands()-1); 3916 DecodePSHUFMask(NumElems, 3917 cast<ConstantSDNode>(ImmN)->getZExtValue(), 3918 ShuffleMask); 3919 break; 3920 case X86ISD::PSHUFHW: 3921 ImmN = N->getOperand(N->getNumOperands()-1); 3922 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 3923 ShuffleMask); 3924 break; 3925 case X86ISD::PSHUFLW: 3926 ImmN = N->getOperand(N->getNumOperands()-1); 3927 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 3928 ShuffleMask); 3929 break; 3930 case X86ISD::MOVSS: 3931 case X86ISD::MOVSD: { 3932 // The index 0 always comes from the first element of the second source, 3933 // this is why MOVSS and MOVSD are used in the first place. The other 3934 // elements come from the other positions of the first source vector. 3935 unsigned OpNum = (Index == 0) ? 1 : 0; 3936 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG, 3937 Depth+1); 3938 } 3939 default: 3940 assert("not implemented for target shuffle node"); 3941 return SDValue(); 3942 } 3943 3944 Index = ShuffleMask[Index]; 3945 if (Index < 0) 3946 return DAG.getUNDEF(VT.getVectorElementType()); 3947 3948 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1); 3949 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, 3950 Depth+1); 3951 } 3952 3953 // Actual nodes that may contain scalar elements 3954 if (Opcode == ISD::BITCAST) { 3955 V = V.getOperand(0); 3956 EVT SrcVT = V.getValueType(); 3957 unsigned NumElems = VT.getVectorNumElements(); 3958 3959 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems) 3960 return SDValue(); 3961 } 3962 3963 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 3964 return (Index == 0) ? V.getOperand(0) 3965 : DAG.getUNDEF(VT.getVectorElementType()); 3966 3967 if (V.getOpcode() == ISD::BUILD_VECTOR) 3968 return V.getOperand(Index); 3969 3970 return SDValue(); 3971} 3972 3973/// getNumOfConsecutiveZeros - Return the number of elements of a vector 3974/// shuffle operation which come from a consecutively from a zero. The 3975/// search can start in two diferent directions, from left or right. 3976static 3977unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems, 3978 bool ZerosFromLeft, SelectionDAG &DAG) { 3979 int i = 0; 3980 3981 while (i < NumElems) { 3982 unsigned Index = ZerosFromLeft ? i : NumElems-i-1; 3983 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0); 3984 if (!(Elt.getNode() && 3985 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt)))) 3986 break; 3987 ++i; 3988 } 3989 3990 return i; 3991} 3992 3993/// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to 3994/// MaskE correspond consecutively to elements from one of the vector operands, 3995/// starting from its index OpIdx. Also tell OpNum which source vector operand. 3996static 3997bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE, 3998 int OpIdx, int NumElems, unsigned &OpNum) { 3999 bool SeenV1 = false; 4000 bool SeenV2 = false; 4001 4002 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) { 4003 int Idx = SVOp->getMaskElt(i); 4004 // Ignore undef indicies 4005 if (Idx < 0) 4006 continue; 4007 4008 if (Idx < NumElems) 4009 SeenV1 = true; 4010 else 4011 SeenV2 = true; 4012 4013 // Only accept consecutive elements from the same vector 4014 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2)) 4015 return false; 4016 } 4017 4018 OpNum = SeenV1 ? 0 : 1; 4019 return true; 4020} 4021 4022/// isVectorShiftRight - Returns true if the shuffle can be implemented as a 4023/// logical left shift of a vector. 4024static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4025 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4026 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4027 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4028 false /* check zeros from right */, DAG); 4029 unsigned OpSrc; 4030 4031 if (!NumZeros) 4032 return false; 4033 4034 // Considering the elements in the mask that are not consecutive zeros, 4035 // check if they consecutively come from only one of the source vectors. 4036 // 4037 // V1 = {X, A, B, C} 0 4038 // \ \ \ / 4039 // vector_shuffle V1, V2 <1, 2, 3, X> 4040 // 4041 if (!isShuffleMaskConsecutive(SVOp, 4042 0, // Mask Start Index 4043 NumElems-NumZeros-1, // Mask End Index 4044 NumZeros, // Where to start looking in the src vector 4045 NumElems, // Number of elements in vector 4046 OpSrc)) // Which source operand ? 4047 return false; 4048 4049 isLeft = false; 4050 ShAmt = NumZeros; 4051 ShVal = SVOp->getOperand(OpSrc); 4052 return true; 4053} 4054 4055/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a 4056/// logical left shift of a vector. 4057static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4058 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4059 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4060 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4061 true /* check zeros from left */, DAG); 4062 unsigned OpSrc; 4063 4064 if (!NumZeros) 4065 return false; 4066 4067 // Considering the elements in the mask that are not consecutive zeros, 4068 // check if they consecutively come from only one of the source vectors. 4069 // 4070 // 0 { A, B, X, X } = V2 4071 // / \ / / 4072 // vector_shuffle V1, V2 <X, X, 4, 5> 4073 // 4074 if (!isShuffleMaskConsecutive(SVOp, 4075 NumZeros, // Mask Start Index 4076 NumElems-1, // Mask End Index 4077 0, // Where to start looking in the src vector 4078 NumElems, // Number of elements in vector 4079 OpSrc)) // Which source operand ? 4080 return false; 4081 4082 isLeft = true; 4083 ShAmt = NumZeros; 4084 ShVal = SVOp->getOperand(OpSrc); 4085 return true; 4086} 4087 4088/// isVectorShift - Returns true if the shuffle can be implemented as a 4089/// logical left or right shift of a vector. 4090static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4091 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4092 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) || 4093 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt)) 4094 return true; 4095 4096 return false; 4097} 4098 4099/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8. 4100/// 4101static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros, 4102 unsigned NumNonZero, unsigned NumZero, 4103 SelectionDAG &DAG, 4104 const TargetLowering &TLI) { 4105 if (NumNonZero > 8) 4106 return SDValue(); 4107 4108 DebugLoc dl = Op.getDebugLoc(); 4109 SDValue V(0, 0); 4110 bool First = true; 4111 for (unsigned i = 0; i < 16; ++i) { 4112 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0; 4113 if (ThisIsNonZero && First) { 4114 if (NumZero) 4115 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4116 else 4117 V = DAG.getUNDEF(MVT::v8i16); 4118 First = false; 4119 } 4120 4121 if ((i & 1) != 0) { 4122 SDValue ThisElt(0, 0), LastElt(0, 0); 4123 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0; 4124 if (LastIsNonZero) { 4125 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl, 4126 MVT::i16, Op.getOperand(i-1)); 4127 } 4128 if (ThisIsNonZero) { 4129 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i)); 4130 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, 4131 ThisElt, DAG.getConstant(8, MVT::i8)); 4132 if (LastIsNonZero) 4133 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt); 4134 } else 4135 ThisElt = LastElt; 4136 4137 if (ThisElt.getNode()) 4138 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt, 4139 DAG.getIntPtrConstant(i/2)); 4140 } 4141 } 4142 4143 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V); 4144} 4145 4146/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16. 4147/// 4148static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros, 4149 unsigned NumNonZero, unsigned NumZero, 4150 SelectionDAG &DAG, 4151 const TargetLowering &TLI) { 4152 if (NumNonZero > 4) 4153 return SDValue(); 4154 4155 DebugLoc dl = Op.getDebugLoc(); 4156 SDValue V(0, 0); 4157 bool First = true; 4158 for (unsigned i = 0; i < 8; ++i) { 4159 bool isNonZero = (NonZeros & (1 << i)) != 0; 4160 if (isNonZero) { 4161 if (First) { 4162 if (NumZero) 4163 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4164 else 4165 V = DAG.getUNDEF(MVT::v8i16); 4166 First = false; 4167 } 4168 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, 4169 MVT::v8i16, V, Op.getOperand(i), 4170 DAG.getIntPtrConstant(i)); 4171 } 4172 } 4173 4174 return V; 4175} 4176 4177/// getVShift - Return a vector logical shift node. 4178/// 4179static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, 4180 unsigned NumBits, SelectionDAG &DAG, 4181 const TargetLowering &TLI, DebugLoc dl) { 4182 EVT ShVT = MVT::v2i64; 4183 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL; 4184 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp); 4185 return DAG.getNode(ISD::BITCAST, dl, VT, 4186 DAG.getNode(Opc, dl, ShVT, SrcOp, 4187 DAG.getConstant(NumBits, 4188 TLI.getShiftAmountTy(SrcOp.getValueType())))); 4189} 4190 4191SDValue 4192X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl, 4193 SelectionDAG &DAG) const { 4194 4195 // Check if the scalar load can be widened into a vector load. And if 4196 // the address is "base + cst" see if the cst can be "absorbed" into 4197 // the shuffle mask. 4198 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) { 4199 SDValue Ptr = LD->getBasePtr(); 4200 if (!ISD::isNormalLoad(LD) || LD->isVolatile()) 4201 return SDValue(); 4202 EVT PVT = LD->getValueType(0); 4203 if (PVT != MVT::i32 && PVT != MVT::f32) 4204 return SDValue(); 4205 4206 int FI = -1; 4207 int64_t Offset = 0; 4208 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) { 4209 FI = FINode->getIndex(); 4210 Offset = 0; 4211 } else if (DAG.isBaseWithConstantOffset(Ptr) && 4212 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 4213 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 4214 Offset = Ptr.getConstantOperandVal(1); 4215 Ptr = Ptr.getOperand(0); 4216 } else { 4217 return SDValue(); 4218 } 4219 4220 SDValue Chain = LD->getChain(); 4221 // Make sure the stack object alignment is at least 16. 4222 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4223 if (DAG.InferPtrAlignment(Ptr) < 16) { 4224 if (MFI->isFixedObjectIndex(FI)) { 4225 // Can't change the alignment. FIXME: It's possible to compute 4226 // the exact stack offset and reference FI + adjust offset instead. 4227 // If someone *really* cares about this. That's the way to implement it. 4228 return SDValue(); 4229 } else { 4230 MFI->setObjectAlignment(FI, 16); 4231 } 4232 } 4233 4234 // (Offset % 16) must be multiple of 4. Then address is then 4235 // Ptr + (Offset & ~15). 4236 if (Offset < 0) 4237 return SDValue(); 4238 if ((Offset % 16) & 3) 4239 return SDValue(); 4240 int64_t StartOffset = Offset & ~15; 4241 if (StartOffset) 4242 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(), 4243 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType())); 4244 4245 int EltNo = (Offset - StartOffset) >> 2; 4246 int Mask[4] = { EltNo, EltNo, EltNo, EltNo }; 4247 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32; 4248 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr, 4249 LD->getPointerInfo().getWithOffset(StartOffset), 4250 false, false, 0); 4251 // Canonicalize it to a v4i32 shuffle. 4252 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 4253 return DAG.getNode(ISD::BITCAST, dl, VT, 4254 DAG.getVectorShuffle(MVT::v4i32, dl, V1, 4255 DAG.getUNDEF(MVT::v4i32),&Mask[0])); 4256 } 4257 4258 return SDValue(); 4259} 4260 4261/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 4262/// vector of type 'VT', see if the elements can be replaced by a single large 4263/// load which has the same value as a build_vector whose operands are 'elts'. 4264/// 4265/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a 4266/// 4267/// FIXME: we'd also like to handle the case where the last elements are zero 4268/// rather than undef via VZEXT_LOAD, but we do not detect that case today. 4269/// There's even a handy isZeroNode for that purpose. 4270static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts, 4271 DebugLoc &DL, SelectionDAG &DAG) { 4272 EVT EltVT = VT.getVectorElementType(); 4273 unsigned NumElems = Elts.size(); 4274 4275 LoadSDNode *LDBase = NULL; 4276 unsigned LastLoadedElt = -1U; 4277 4278 // For each element in the initializer, see if we've found a load or an undef. 4279 // If we don't find an initial load element, or later load elements are 4280 // non-consecutive, bail out. 4281 for (unsigned i = 0; i < NumElems; ++i) { 4282 SDValue Elt = Elts[i]; 4283 4284 if (!Elt.getNode() || 4285 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode()))) 4286 return SDValue(); 4287 if (!LDBase) { 4288 if (Elt.getNode()->getOpcode() == ISD::UNDEF) 4289 return SDValue(); 4290 LDBase = cast<LoadSDNode>(Elt.getNode()); 4291 LastLoadedElt = i; 4292 continue; 4293 } 4294 if (Elt.getOpcode() == ISD::UNDEF) 4295 continue; 4296 4297 LoadSDNode *LD = cast<LoadSDNode>(Elt); 4298 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i)) 4299 return SDValue(); 4300 LastLoadedElt = i; 4301 } 4302 4303 // If we have found an entire vector of loads and undefs, then return a large 4304 // load of the entire vector width starting at the base pointer. If we found 4305 // consecutive loads for the low half, generate a vzext_load node. 4306 if (LastLoadedElt == NumElems - 1) { 4307 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16) 4308 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 4309 LDBase->getPointerInfo(), 4310 LDBase->isVolatile(), LDBase->isNonTemporal(), 0); 4311 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 4312 LDBase->getPointerInfo(), 4313 LDBase->isVolatile(), LDBase->isNonTemporal(), 4314 LDBase->getAlignment()); 4315 } else if (NumElems == 4 && LastLoadedElt == 1) { 4316 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other); 4317 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() }; 4318 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, 4319 Ops, 2, MVT::i32, 4320 LDBase->getMemOperand()); 4321 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode); 4322 } 4323 return SDValue(); 4324} 4325 4326SDValue 4327X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { 4328 DebugLoc dl = Op.getDebugLoc(); 4329 4330 EVT VT = Op.getValueType(); 4331 EVT ExtVT = VT.getVectorElementType(); 4332 4333 unsigned NumElems = Op.getNumOperands(); 4334 4335 // For AVX-length vectors, build the individual 128-bit pieces and 4336 // use shuffles to put them in place. 4337 if (VT.getSizeInBits() > 256 && 4338 Subtarget->hasAVX() && 4339 !ISD::isBuildVectorAllZeros(Op.getNode())) { 4340 SmallVector<SDValue, 8> V; 4341 V.resize(NumElems); 4342 for (unsigned i = 0; i < NumElems; ++i) { 4343 V[i] = Op.getOperand(i); 4344 } 4345 4346 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2); 4347 4348 // Build the lower subvector. 4349 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2); 4350 // Build the upper subvector. 4351 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2], 4352 NumElems/2); 4353 4354 return ConcatVectors(Lower, Upper, DAG); 4355 } 4356 4357 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1. 4358 // All one's are handled with pcmpeqd. In AVX, zero's are handled with 4359 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd 4360 // is present, so AllOnes is ignored. 4361 if (ISD::isBuildVectorAllZeros(Op.getNode()) || 4362 (Op.getValueType().getSizeInBits() != 256 && 4363 ISD::isBuildVectorAllOnes(Op.getNode()))) { 4364 // Canonicalize this to <4 x i32> (SSE) to 4365 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are 4366 // eliminated on x86-32 hosts. 4367 if (Op.getValueType() == MVT::v4i32) 4368 return Op; 4369 4370 if (ISD::isBuildVectorAllOnes(Op.getNode())) 4371 return getOnesVector(Op.getValueType(), DAG, dl); 4372 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl); 4373 } 4374 4375 unsigned EVTBits = ExtVT.getSizeInBits(); 4376 4377 unsigned NumZero = 0; 4378 unsigned NumNonZero = 0; 4379 unsigned NonZeros = 0; 4380 bool IsAllConstants = true; 4381 SmallSet<SDValue, 8> Values; 4382 for (unsigned i = 0; i < NumElems; ++i) { 4383 SDValue Elt = Op.getOperand(i); 4384 if (Elt.getOpcode() == ISD::UNDEF) 4385 continue; 4386 Values.insert(Elt); 4387 if (Elt.getOpcode() != ISD::Constant && 4388 Elt.getOpcode() != ISD::ConstantFP) 4389 IsAllConstants = false; 4390 if (X86::isZeroNode(Elt)) 4391 NumZero++; 4392 else { 4393 NonZeros |= (1 << i); 4394 NumNonZero++; 4395 } 4396 } 4397 4398 // All undef vector. Return an UNDEF. All zero vectors were handled above. 4399 if (NumNonZero == 0) 4400 return DAG.getUNDEF(VT); 4401 4402 // Special case for single non-zero, non-undef, element. 4403 if (NumNonZero == 1) { 4404 unsigned Idx = CountTrailingZeros_32(NonZeros); 4405 SDValue Item = Op.getOperand(Idx); 4406 4407 // If this is an insertion of an i64 value on x86-32, and if the top bits of 4408 // the value are obviously zero, truncate the value to i32 and do the 4409 // insertion that way. Only do this if the value is non-constant or if the 4410 // value is a constant being inserted into element 0. It is cheaper to do 4411 // a constant pool load than it is to do a movd + shuffle. 4412 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() && 4413 (!IsAllConstants || Idx == 0)) { 4414 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) { 4415 // Handle SSE only. 4416 assert(VT == MVT::v2i64 && "Expected an SSE value type!"); 4417 EVT VecVT = MVT::v4i32; 4418 unsigned VecElts = 4; 4419 4420 // Truncate the value (which may itself be a constant) to i32, and 4421 // convert it to a vector with movd (S2V+shuffle to zero extend). 4422 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item); 4423 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item); 4424 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 4425 Subtarget->hasSSE2(), DAG); 4426 4427 // Now we have our 32-bit value zero extended in the low element of 4428 // a vector. If Idx != 0, swizzle it into place. 4429 if (Idx != 0) { 4430 SmallVector<int, 4> Mask; 4431 Mask.push_back(Idx); 4432 for (unsigned i = 1; i != VecElts; ++i) 4433 Mask.push_back(i); 4434 Item = DAG.getVectorShuffle(VecVT, dl, Item, 4435 DAG.getUNDEF(Item.getValueType()), 4436 &Mask[0]); 4437 } 4438 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item); 4439 } 4440 } 4441 4442 // If we have a constant or non-constant insertion into the low element of 4443 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into 4444 // the rest of the elements. This will be matched as movd/movq/movss/movsd 4445 // depending on what the source datatype is. 4446 if (Idx == 0) { 4447 if (NumZero == 0) { 4448 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 4449 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 || 4450 (ExtVT == MVT::i64 && Subtarget->is64Bit())) { 4451 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 4452 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector. 4453 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(), 4454 DAG); 4455 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) { 4456 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item); 4457 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!"); 4458 EVT MiddleVT = MVT::v4i32; 4459 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item); 4460 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 4461 Subtarget->hasSSE2(), DAG); 4462 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 4463 } 4464 } 4465 4466 // Is it a vector logical left shift? 4467 if (NumElems == 2 && Idx == 1 && 4468 X86::isZeroNode(Op.getOperand(0)) && 4469 !X86::isZeroNode(Op.getOperand(1))) { 4470 unsigned NumBits = VT.getSizeInBits(); 4471 return getVShift(true, VT, 4472 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 4473 VT, Op.getOperand(1)), 4474 NumBits/2, DAG, *this, dl); 4475 } 4476 4477 if (IsAllConstants) // Otherwise, it's better to do a constpool load. 4478 return SDValue(); 4479 4480 // Otherwise, if this is a vector with i32 or f32 elements, and the element 4481 // is a non-constant being inserted into an element other than the low one, 4482 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka 4483 // movd/movss) to move this into the low element, then shuffle it into 4484 // place. 4485 if (EVTBits == 32) { 4486 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 4487 4488 // Turn it into a shuffle of zero and zero-extended scalar to vector. 4489 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, 4490 Subtarget->hasSSE2(), DAG); 4491 SmallVector<int, 8> MaskVec; 4492 for (unsigned i = 0; i < NumElems; i++) 4493 MaskVec.push_back(i == Idx ? 0 : 1); 4494 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]); 4495 } 4496 } 4497 4498 // Splat is obviously ok. Let legalizer expand it to a shuffle. 4499 if (Values.size() == 1) { 4500 if (EVTBits == 32) { 4501 // Instead of a shuffle like this: 4502 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0> 4503 // Check if it's possible to issue this instead. 4504 // shuffle (vload ptr)), undef, <1, 1, 1, 1> 4505 unsigned Idx = CountTrailingZeros_32(NonZeros); 4506 SDValue Item = Op.getOperand(Idx); 4507 if (Op.getNode()->isOnlyUserOf(Item.getNode())) 4508 return LowerAsSplatVectorLoad(Item, VT, dl, DAG); 4509 } 4510 return SDValue(); 4511 } 4512 4513 // A vector full of immediates; various special cases are already 4514 // handled, so this is best done with a single constant-pool load. 4515 if (IsAllConstants) 4516 return SDValue(); 4517 4518 // Let legalizer expand 2-wide build_vectors. 4519 if (EVTBits == 64) { 4520 if (NumNonZero == 1) { 4521 // One half is zero or undef. 4522 unsigned Idx = CountTrailingZeros_32(NonZeros); 4523 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, 4524 Op.getOperand(Idx)); 4525 return getShuffleVectorZeroOrUndef(V2, Idx, true, 4526 Subtarget->hasSSE2(), DAG); 4527 } 4528 return SDValue(); 4529 } 4530 4531 // If element VT is < 32 bits, convert it to inserts into a zero vector. 4532 if (EVTBits == 8 && NumElems == 16) { 4533 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG, 4534 *this); 4535 if (V.getNode()) return V; 4536 } 4537 4538 if (EVTBits == 16 && NumElems == 8) { 4539 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG, 4540 *this); 4541 if (V.getNode()) return V; 4542 } 4543 4544 // If element VT is == 32 bits, turn it into a number of shuffles. 4545 SmallVector<SDValue, 8> V; 4546 V.resize(NumElems); 4547 if (NumElems == 4 && NumZero > 0) { 4548 for (unsigned i = 0; i < 4; ++i) { 4549 bool isZero = !(NonZeros & (1 << i)); 4550 if (isZero) 4551 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl); 4552 else 4553 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 4554 } 4555 4556 for (unsigned i = 0; i < 2; ++i) { 4557 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) { 4558 default: break; 4559 case 0: 4560 V[i] = V[i*2]; // Must be a zero vector. 4561 break; 4562 case 1: 4563 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]); 4564 break; 4565 case 2: 4566 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]); 4567 break; 4568 case 3: 4569 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]); 4570 break; 4571 } 4572 } 4573 4574 SmallVector<int, 8> MaskVec; 4575 bool Reverse = (NonZeros & 0x3) == 2; 4576 for (unsigned i = 0; i < 2; ++i) 4577 MaskVec.push_back(Reverse ? 1-i : i); 4578 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2; 4579 for (unsigned i = 0; i < 2; ++i) 4580 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems); 4581 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]); 4582 } 4583 4584 if (Values.size() > 1 && VT.getSizeInBits() == 128) { 4585 // Check for a build vector of consecutive loads. 4586 for (unsigned i = 0; i < NumElems; ++i) 4587 V[i] = Op.getOperand(i); 4588 4589 // Check for elements which are consecutive loads. 4590 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG); 4591 if (LD.getNode()) 4592 return LD; 4593 4594 // For SSE 4.1, use insertps to put the high elements into the low element. 4595 if (getSubtarget()->hasSSE41()) { 4596 SDValue Result; 4597 if (Op.getOperand(0).getOpcode() != ISD::UNDEF) 4598 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0)); 4599 else 4600 Result = DAG.getUNDEF(VT); 4601 4602 for (unsigned i = 1; i < NumElems; ++i) { 4603 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue; 4604 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result, 4605 Op.getOperand(i), DAG.getIntPtrConstant(i)); 4606 } 4607 return Result; 4608 } 4609 4610 // Otherwise, expand into a number of unpckl*, start by extending each of 4611 // our (non-undef) elements to the full vector width with the element in the 4612 // bottom slot of the vector (which generates no code for SSE). 4613 for (unsigned i = 0; i < NumElems; ++i) { 4614 if (Op.getOperand(i).getOpcode() != ISD::UNDEF) 4615 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 4616 else 4617 V[i] = DAG.getUNDEF(VT); 4618 } 4619 4620 // Next, we iteratively mix elements, e.g. for v4f32: 4621 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0> 4622 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1> 4623 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0> 4624 unsigned EltStride = NumElems >> 1; 4625 while (EltStride != 0) { 4626 for (unsigned i = 0; i < EltStride; ++i) { 4627 // If V[i+EltStride] is undef and this is the first round of mixing, 4628 // then it is safe to just drop this shuffle: V[i] is already in the 4629 // right place, the one element (since it's the first round) being 4630 // inserted as undef can be dropped. This isn't safe for successive 4631 // rounds because they will permute elements within both vectors. 4632 if (V[i+EltStride].getOpcode() == ISD::UNDEF && 4633 EltStride == NumElems/2) 4634 continue; 4635 4636 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]); 4637 } 4638 EltStride >>= 1; 4639 } 4640 return V[0]; 4641 } 4642 return SDValue(); 4643} 4644 4645SDValue 4646X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const { 4647 // We support concatenate two MMX registers and place them in a MMX 4648 // register. This is better than doing a stack convert. 4649 DebugLoc dl = Op.getDebugLoc(); 4650 EVT ResVT = Op.getValueType(); 4651 assert(Op.getNumOperands() == 2); 4652 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 || 4653 ResVT == MVT::v8i16 || ResVT == MVT::v16i8); 4654 int Mask[2]; 4655 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0)); 4656 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 4657 InVec = Op.getOperand(1); 4658 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 4659 unsigned NumElts = ResVT.getVectorNumElements(); 4660 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 4661 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp, 4662 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1)); 4663 } else { 4664 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec); 4665 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 4666 Mask[0] = 0; Mask[1] = 2; 4667 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask); 4668 } 4669 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 4670} 4671 4672// v8i16 shuffles - Prefer shuffles in the following order: 4673// 1. [all] pshuflw, pshufhw, optional move 4674// 2. [ssse3] 1 x pshufb 4675// 3. [ssse3] 2 x pshufb + 1 x por 4676// 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw) 4677SDValue 4678X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op, 4679 SelectionDAG &DAG) const { 4680 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 4681 SDValue V1 = SVOp->getOperand(0); 4682 SDValue V2 = SVOp->getOperand(1); 4683 DebugLoc dl = SVOp->getDebugLoc(); 4684 SmallVector<int, 8> MaskVals; 4685 4686 // Determine if more than 1 of the words in each of the low and high quadwords 4687 // of the result come from the same quadword of one of the two inputs. Undef 4688 // mask values count as coming from any quadword, for better codegen. 4689 SmallVector<unsigned, 4> LoQuad(4); 4690 SmallVector<unsigned, 4> HiQuad(4); 4691 BitVector InputQuads(4); 4692 for (unsigned i = 0; i < 8; ++i) { 4693 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad; 4694 int EltIdx = SVOp->getMaskElt(i); 4695 MaskVals.push_back(EltIdx); 4696 if (EltIdx < 0) { 4697 ++Quad[0]; 4698 ++Quad[1]; 4699 ++Quad[2]; 4700 ++Quad[3]; 4701 continue; 4702 } 4703 ++Quad[EltIdx / 4]; 4704 InputQuads.set(EltIdx / 4); 4705 } 4706 4707 int BestLoQuad = -1; 4708 unsigned MaxQuad = 1; 4709 for (unsigned i = 0; i < 4; ++i) { 4710 if (LoQuad[i] > MaxQuad) { 4711 BestLoQuad = i; 4712 MaxQuad = LoQuad[i]; 4713 } 4714 } 4715 4716 int BestHiQuad = -1; 4717 MaxQuad = 1; 4718 for (unsigned i = 0; i < 4; ++i) { 4719 if (HiQuad[i] > MaxQuad) { 4720 BestHiQuad = i; 4721 MaxQuad = HiQuad[i]; 4722 } 4723 } 4724 4725 // For SSSE3, If all 8 words of the result come from only 1 quadword of each 4726 // of the two input vectors, shuffle them into one input vector so only a 4727 // single pshufb instruction is necessary. If There are more than 2 input 4728 // quads, disable the next transformation since it does not help SSSE3. 4729 bool V1Used = InputQuads[0] || InputQuads[1]; 4730 bool V2Used = InputQuads[2] || InputQuads[3]; 4731 if (Subtarget->hasSSSE3()) { 4732 if (InputQuads.count() == 2 && V1Used && V2Used) { 4733 BestLoQuad = InputQuads.find_first(); 4734 BestHiQuad = InputQuads.find_next(BestLoQuad); 4735 } 4736 if (InputQuads.count() > 2) { 4737 BestLoQuad = -1; 4738 BestHiQuad = -1; 4739 } 4740 } 4741 4742 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update 4743 // the shuffle mask. If a quad is scored as -1, that means that it contains 4744 // words from all 4 input quadwords. 4745 SDValue NewV; 4746 if (BestLoQuad >= 0 || BestHiQuad >= 0) { 4747 SmallVector<int, 8> MaskV; 4748 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad); 4749 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad); 4750 NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 4751 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1), 4752 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]); 4753 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV); 4754 4755 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the 4756 // source words for the shuffle, to aid later transformations. 4757 bool AllWordsInNewV = true; 4758 bool InOrder[2] = { true, true }; 4759 for (unsigned i = 0; i != 8; ++i) { 4760 int idx = MaskVals[i]; 4761 if (idx != (int)i) 4762 InOrder[i/4] = false; 4763 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad) 4764 continue; 4765 AllWordsInNewV = false; 4766 break; 4767 } 4768 4769 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV; 4770 if (AllWordsInNewV) { 4771 for (int i = 0; i != 8; ++i) { 4772 int idx = MaskVals[i]; 4773 if (idx < 0) 4774 continue; 4775 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 4776 if ((idx != i) && idx < 4) 4777 pshufhw = false; 4778 if ((idx != i) && idx > 3) 4779 pshuflw = false; 4780 } 4781 V1 = NewV; 4782 V2Used = false; 4783 BestLoQuad = 0; 4784 BestHiQuad = 1; 4785 } 4786 4787 // If we've eliminated the use of V2, and the new mask is a pshuflw or 4788 // pshufhw, that's as cheap as it gets. Return the new shuffle. 4789 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) { 4790 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW; 4791 unsigned TargetMask = 0; 4792 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 4793 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]); 4794 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()): 4795 X86::getShufflePSHUFLWImmediate(NewV.getNode()); 4796 V1 = NewV.getOperand(0); 4797 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG); 4798 } 4799 } 4800 4801 // If we have SSSE3, and all words of the result are from 1 input vector, 4802 // case 2 is generated, otherwise case 3 is generated. If no SSSE3 4803 // is present, fall back to case 4. 4804 if (Subtarget->hasSSSE3()) { 4805 SmallVector<SDValue,16> pshufbMask; 4806 4807 // If we have elements from both input vectors, set the high bit of the 4808 // shuffle mask element to zero out elements that come from V2 in the V1 4809 // mask, and elements that come from V1 in the V2 mask, so that the two 4810 // results can be OR'd together. 4811 bool TwoInputs = V1Used && V2Used; 4812 for (unsigned i = 0; i != 8; ++i) { 4813 int EltIdx = MaskVals[i] * 2; 4814 if (TwoInputs && (EltIdx >= 16)) { 4815 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4816 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4817 continue; 4818 } 4819 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 4820 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8)); 4821 } 4822 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1); 4823 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 4824 DAG.getNode(ISD::BUILD_VECTOR, dl, 4825 MVT::v16i8, &pshufbMask[0], 16)); 4826 if (!TwoInputs) 4827 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 4828 4829 // Calculate the shuffle mask for the second input, shuffle it, and 4830 // OR it with the first shuffled input. 4831 pshufbMask.clear(); 4832 for (unsigned i = 0; i != 8; ++i) { 4833 int EltIdx = MaskVals[i] * 2; 4834 if (EltIdx < 16) { 4835 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4836 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4837 continue; 4838 } 4839 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 4840 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8)); 4841 } 4842 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2); 4843 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 4844 DAG.getNode(ISD::BUILD_VECTOR, dl, 4845 MVT::v16i8, &pshufbMask[0], 16)); 4846 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 4847 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 4848 } 4849 4850 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order, 4851 // and update MaskVals with new element order. 4852 BitVector InOrder(8); 4853 if (BestLoQuad >= 0) { 4854 SmallVector<int, 8> MaskV; 4855 for (int i = 0; i != 4; ++i) { 4856 int idx = MaskVals[i]; 4857 if (idx < 0) { 4858 MaskV.push_back(-1); 4859 InOrder.set(i); 4860 } else if ((idx / 4) == BestLoQuad) { 4861 MaskV.push_back(idx & 3); 4862 InOrder.set(i); 4863 } else { 4864 MaskV.push_back(-1); 4865 } 4866 } 4867 for (unsigned i = 4; i != 8; ++i) 4868 MaskV.push_back(i); 4869 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 4870 &MaskV[0]); 4871 4872 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) 4873 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16, 4874 NewV.getOperand(0), 4875 X86::getShufflePSHUFLWImmediate(NewV.getNode()), 4876 DAG); 4877 } 4878 4879 // If BestHi >= 0, generate a pshufhw to put the high elements in order, 4880 // and update MaskVals with the new element order. 4881 if (BestHiQuad >= 0) { 4882 SmallVector<int, 8> MaskV; 4883 for (unsigned i = 0; i != 4; ++i) 4884 MaskV.push_back(i); 4885 for (unsigned i = 4; i != 8; ++i) { 4886 int idx = MaskVals[i]; 4887 if (idx < 0) { 4888 MaskV.push_back(-1); 4889 InOrder.set(i); 4890 } else if ((idx / 4) == BestHiQuad) { 4891 MaskV.push_back((idx & 3) + 4); 4892 InOrder.set(i); 4893 } else { 4894 MaskV.push_back(-1); 4895 } 4896 } 4897 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 4898 &MaskV[0]); 4899 4900 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) 4901 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16, 4902 NewV.getOperand(0), 4903 X86::getShufflePSHUFHWImmediate(NewV.getNode()), 4904 DAG); 4905 } 4906 4907 // In case BestHi & BestLo were both -1, which means each quadword has a word 4908 // from each of the four input quadwords, calculate the InOrder bitvector now 4909 // before falling through to the insert/extract cleanup. 4910 if (BestLoQuad == -1 && BestHiQuad == -1) { 4911 NewV = V1; 4912 for (int i = 0; i != 8; ++i) 4913 if (MaskVals[i] < 0 || MaskVals[i] == i) 4914 InOrder.set(i); 4915 } 4916 4917 // The other elements are put in the right place using pextrw and pinsrw. 4918 for (unsigned i = 0; i != 8; ++i) { 4919 if (InOrder[i]) 4920 continue; 4921 int EltIdx = MaskVals[i]; 4922 if (EltIdx < 0) 4923 continue; 4924 SDValue ExtOp = (EltIdx < 8) 4925 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1, 4926 DAG.getIntPtrConstant(EltIdx)) 4927 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2, 4928 DAG.getIntPtrConstant(EltIdx - 8)); 4929 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp, 4930 DAG.getIntPtrConstant(i)); 4931 } 4932 return NewV; 4933} 4934 4935// v16i8 shuffles - Prefer shuffles in the following order: 4936// 1. [ssse3] 1 x pshufb 4937// 2. [ssse3] 2 x pshufb + 1 x por 4938// 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw 4939static 4940SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp, 4941 SelectionDAG &DAG, 4942 const X86TargetLowering &TLI) { 4943 SDValue V1 = SVOp->getOperand(0); 4944 SDValue V2 = SVOp->getOperand(1); 4945 DebugLoc dl = SVOp->getDebugLoc(); 4946 SmallVector<int, 16> MaskVals; 4947 SVOp->getMask(MaskVals); 4948 4949 // If we have SSSE3, case 1 is generated when all result bytes come from 4950 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is 4951 // present, fall back to case 3. 4952 // FIXME: kill V2Only once shuffles are canonizalized by getNode. 4953 bool V1Only = true; 4954 bool V2Only = true; 4955 for (unsigned i = 0; i < 16; ++i) { 4956 int EltIdx = MaskVals[i]; 4957 if (EltIdx < 0) 4958 continue; 4959 if (EltIdx < 16) 4960 V2Only = false; 4961 else 4962 V1Only = false; 4963 } 4964 4965 // If SSSE3, use 1 pshufb instruction per vector with elements in the result. 4966 if (TLI.getSubtarget()->hasSSSE3()) { 4967 SmallVector<SDValue,16> pshufbMask; 4968 4969 // If all result elements are from one input vector, then only translate 4970 // undef mask values to 0x80 (zero out result) in the pshufb mask. 4971 // 4972 // Otherwise, we have elements from both input vectors, and must zero out 4973 // elements that come from V2 in the first mask, and V1 in the second mask 4974 // so that we can OR them together. 4975 bool TwoInputs = !(V1Only || V2Only); 4976 for (unsigned i = 0; i != 16; ++i) { 4977 int EltIdx = MaskVals[i]; 4978 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) { 4979 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4980 continue; 4981 } 4982 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 4983 } 4984 // If all the elements are from V2, assign it to V1 and return after 4985 // building the first pshufb. 4986 if (V2Only) 4987 V1 = V2; 4988 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 4989 DAG.getNode(ISD::BUILD_VECTOR, dl, 4990 MVT::v16i8, &pshufbMask[0], 16)); 4991 if (!TwoInputs) 4992 return V1; 4993 4994 // Calculate the shuffle mask for the second input, shuffle it, and 4995 // OR it with the first shuffled input. 4996 pshufbMask.clear(); 4997 for (unsigned i = 0; i != 16; ++i) { 4998 int EltIdx = MaskVals[i]; 4999 if (EltIdx < 16) { 5000 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5001 continue; 5002 } 5003 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 5004 } 5005 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5006 DAG.getNode(ISD::BUILD_VECTOR, dl, 5007 MVT::v16i8, &pshufbMask[0], 16)); 5008 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5009 } 5010 5011 // No SSSE3 - Calculate in place words and then fix all out of place words 5012 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from 5013 // the 16 different words that comprise the two doublequadword input vectors. 5014 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5015 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 5016 SDValue NewV = V2Only ? V2 : V1; 5017 for (int i = 0; i != 8; ++i) { 5018 int Elt0 = MaskVals[i*2]; 5019 int Elt1 = MaskVals[i*2+1]; 5020 5021 // This word of the result is all undef, skip it. 5022 if (Elt0 < 0 && Elt1 < 0) 5023 continue; 5024 5025 // This word of the result is already in the correct place, skip it. 5026 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1)) 5027 continue; 5028 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17)) 5029 continue; 5030 5031 SDValue Elt0Src = Elt0 < 16 ? V1 : V2; 5032 SDValue Elt1Src = Elt1 < 16 ? V1 : V2; 5033 SDValue InsElt; 5034 5035 // If Elt0 and Elt1 are defined, are consecutive, and can be load 5036 // using a single extract together, load it and store it. 5037 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) { 5038 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5039 DAG.getIntPtrConstant(Elt1 / 2)); 5040 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5041 DAG.getIntPtrConstant(i)); 5042 continue; 5043 } 5044 5045 // If Elt1 is defined, extract it from the appropriate source. If the 5046 // source byte is not also odd, shift the extracted word left 8 bits 5047 // otherwise clear the bottom 8 bits if we need to do an or. 5048 if (Elt1 >= 0) { 5049 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5050 DAG.getIntPtrConstant(Elt1 / 2)); 5051 if ((Elt1 & 1) == 0) 5052 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt, 5053 DAG.getConstant(8, 5054 TLI.getShiftAmountTy(InsElt.getValueType()))); 5055 else if (Elt0 >= 0) 5056 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt, 5057 DAG.getConstant(0xFF00, MVT::i16)); 5058 } 5059 // If Elt0 is defined, extract it from the appropriate source. If the 5060 // source byte is not also even, shift the extracted word right 8 bits. If 5061 // Elt1 was also defined, OR the extracted values together before 5062 // inserting them in the result. 5063 if (Elt0 >= 0) { 5064 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, 5065 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2)); 5066 if ((Elt0 & 1) != 0) 5067 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0, 5068 DAG.getConstant(8, 5069 TLI.getShiftAmountTy(InsElt0.getValueType()))); 5070 else if (Elt1 >= 0) 5071 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0, 5072 DAG.getConstant(0x00FF, MVT::i16)); 5073 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0) 5074 : InsElt0; 5075 } 5076 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5077 DAG.getIntPtrConstant(i)); 5078 } 5079 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV); 5080} 5081 5082/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide 5083/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be 5084/// done when every pair / quad of shuffle mask elements point to elements in 5085/// the right sequence. e.g. 5086/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15> 5087static 5088SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp, 5089 SelectionDAG &DAG, DebugLoc dl) { 5090 EVT VT = SVOp->getValueType(0); 5091 SDValue V1 = SVOp->getOperand(0); 5092 SDValue V2 = SVOp->getOperand(1); 5093 unsigned NumElems = VT.getVectorNumElements(); 5094 unsigned NewWidth = (NumElems == 4) ? 2 : 4; 5095 EVT NewVT; 5096 switch (VT.getSimpleVT().SimpleTy) { 5097 default: assert(false && "Unexpected!"); 5098 case MVT::v4f32: NewVT = MVT::v2f64; break; 5099 case MVT::v4i32: NewVT = MVT::v2i64; break; 5100 case MVT::v8i16: NewVT = MVT::v4i32; break; 5101 case MVT::v16i8: NewVT = MVT::v4i32; break; 5102 } 5103 5104 int Scale = NumElems / NewWidth; 5105 SmallVector<int, 8> MaskVec; 5106 for (unsigned i = 0; i < NumElems; i += Scale) { 5107 int StartIdx = -1; 5108 for (int j = 0; j < Scale; ++j) { 5109 int EltIdx = SVOp->getMaskElt(i+j); 5110 if (EltIdx < 0) 5111 continue; 5112 if (StartIdx == -1) 5113 StartIdx = EltIdx - (EltIdx % Scale); 5114 if (EltIdx != StartIdx + j) 5115 return SDValue(); 5116 } 5117 if (StartIdx == -1) 5118 MaskVec.push_back(-1); 5119 else 5120 MaskVec.push_back(StartIdx / Scale); 5121 } 5122 5123 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1); 5124 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2); 5125 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]); 5126} 5127 5128/// getVZextMovL - Return a zero-extending vector move low node. 5129/// 5130static SDValue getVZextMovL(EVT VT, EVT OpVT, 5131 SDValue SrcOp, SelectionDAG &DAG, 5132 const X86Subtarget *Subtarget, DebugLoc dl) { 5133 if (VT == MVT::v2f64 || VT == MVT::v4f32) { 5134 LoadSDNode *LD = NULL; 5135 if (!isScalarLoadToVector(SrcOp.getNode(), &LD)) 5136 LD = dyn_cast<LoadSDNode>(SrcOp); 5137 if (!LD) { 5138 // movssrr and movsdrr do not clear top bits. Try to use movd, movq 5139 // instead. 5140 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32; 5141 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) && 5142 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 5143 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST && 5144 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) { 5145 // PR2108 5146 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32; 5147 return DAG.getNode(ISD::BITCAST, dl, VT, 5148 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 5149 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5150 OpVT, 5151 SrcOp.getOperand(0) 5152 .getOperand(0)))); 5153 } 5154 } 5155 } 5156 5157 return DAG.getNode(ISD::BITCAST, dl, VT, 5158 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 5159 DAG.getNode(ISD::BITCAST, dl, 5160 OpVT, SrcOp))); 5161} 5162 5163/// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of 5164/// shuffles. 5165static SDValue 5166LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 5167 SDValue V1 = SVOp->getOperand(0); 5168 SDValue V2 = SVOp->getOperand(1); 5169 DebugLoc dl = SVOp->getDebugLoc(); 5170 EVT VT = SVOp->getValueType(0); 5171 5172 SmallVector<std::pair<int, int>, 8> Locs; 5173 Locs.resize(4); 5174 SmallVector<int, 8> Mask1(4U, -1); 5175 SmallVector<int, 8> PermMask; 5176 SVOp->getMask(PermMask); 5177 5178 unsigned NumHi = 0; 5179 unsigned NumLo = 0; 5180 for (unsigned i = 0; i != 4; ++i) { 5181 int Idx = PermMask[i]; 5182 if (Idx < 0) { 5183 Locs[i] = std::make_pair(-1, -1); 5184 } else { 5185 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!"); 5186 if (Idx < 4) { 5187 Locs[i] = std::make_pair(0, NumLo); 5188 Mask1[NumLo] = Idx; 5189 NumLo++; 5190 } else { 5191 Locs[i] = std::make_pair(1, NumHi); 5192 if (2+NumHi < 4) 5193 Mask1[2+NumHi] = Idx; 5194 NumHi++; 5195 } 5196 } 5197 } 5198 5199 if (NumLo <= 2 && NumHi <= 2) { 5200 // If no more than two elements come from either vector. This can be 5201 // implemented with two shuffles. First shuffle gather the elements. 5202 // The second shuffle, which takes the first shuffle as both of its 5203 // vector operands, put the elements into the right order. 5204 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 5205 5206 SmallVector<int, 8> Mask2(4U, -1); 5207 5208 for (unsigned i = 0; i != 4; ++i) { 5209 if (Locs[i].first == -1) 5210 continue; 5211 else { 5212 unsigned Idx = (i < 2) ? 0 : 4; 5213 Idx += Locs[i].first * 2 + Locs[i].second; 5214 Mask2[i] = Idx; 5215 } 5216 } 5217 5218 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]); 5219 } else if (NumLo == 3 || NumHi == 3) { 5220 // Otherwise, we must have three elements from one vector, call it X, and 5221 // one element from the other, call it Y. First, use a shufps to build an 5222 // intermediate vector with the one element from Y and the element from X 5223 // that will be in the same half in the final destination (the indexes don't 5224 // matter). Then, use a shufps to build the final vector, taking the half 5225 // containing the element from Y from the intermediate, and the other half 5226 // from X. 5227 if (NumHi == 3) { 5228 // Normalize it so the 3 elements come from V1. 5229 CommuteVectorShuffleMask(PermMask, VT); 5230 std::swap(V1, V2); 5231 } 5232 5233 // Find the element from V2. 5234 unsigned HiIndex; 5235 for (HiIndex = 0; HiIndex < 3; ++HiIndex) { 5236 int Val = PermMask[HiIndex]; 5237 if (Val < 0) 5238 continue; 5239 if (Val >= 4) 5240 break; 5241 } 5242 5243 Mask1[0] = PermMask[HiIndex]; 5244 Mask1[1] = -1; 5245 Mask1[2] = PermMask[HiIndex^1]; 5246 Mask1[3] = -1; 5247 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 5248 5249 if (HiIndex >= 2) { 5250 Mask1[0] = PermMask[0]; 5251 Mask1[1] = PermMask[1]; 5252 Mask1[2] = HiIndex & 1 ? 6 : 4; 5253 Mask1[3] = HiIndex & 1 ? 4 : 6; 5254 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 5255 } else { 5256 Mask1[0] = HiIndex & 1 ? 2 : 0; 5257 Mask1[1] = HiIndex & 1 ? 0 : 2; 5258 Mask1[2] = PermMask[2]; 5259 Mask1[3] = PermMask[3]; 5260 if (Mask1[2] >= 0) 5261 Mask1[2] += 4; 5262 if (Mask1[3] >= 0) 5263 Mask1[3] += 4; 5264 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]); 5265 } 5266 } 5267 5268 // Break it into (shuffle shuffle_hi, shuffle_lo). 5269 Locs.clear(); 5270 Locs.resize(4); 5271 SmallVector<int,8> LoMask(4U, -1); 5272 SmallVector<int,8> HiMask(4U, -1); 5273 5274 SmallVector<int,8> *MaskPtr = &LoMask; 5275 unsigned MaskIdx = 0; 5276 unsigned LoIdx = 0; 5277 unsigned HiIdx = 2; 5278 for (unsigned i = 0; i != 4; ++i) { 5279 if (i == 2) { 5280 MaskPtr = &HiMask; 5281 MaskIdx = 1; 5282 LoIdx = 0; 5283 HiIdx = 2; 5284 } 5285 int Idx = PermMask[i]; 5286 if (Idx < 0) { 5287 Locs[i] = std::make_pair(-1, -1); 5288 } else if (Idx < 4) { 5289 Locs[i] = std::make_pair(MaskIdx, LoIdx); 5290 (*MaskPtr)[LoIdx] = Idx; 5291 LoIdx++; 5292 } else { 5293 Locs[i] = std::make_pair(MaskIdx, HiIdx); 5294 (*MaskPtr)[HiIdx] = Idx; 5295 HiIdx++; 5296 } 5297 } 5298 5299 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]); 5300 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]); 5301 SmallVector<int, 8> MaskOps; 5302 for (unsigned i = 0; i != 4; ++i) { 5303 if (Locs[i].first == -1) { 5304 MaskOps.push_back(-1); 5305 } else { 5306 unsigned Idx = Locs[i].first * 4 + Locs[i].second; 5307 MaskOps.push_back(Idx); 5308 } 5309 } 5310 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]); 5311} 5312 5313static bool MayFoldVectorLoad(SDValue V) { 5314 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 5315 V = V.getOperand(0); 5316 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 5317 V = V.getOperand(0); 5318 if (MayFoldLoad(V)) 5319 return true; 5320 return false; 5321} 5322 5323// FIXME: the version above should always be used. Since there's 5324// a bug where several vector shuffles can't be folded because the 5325// DAG is not updated during lowering and a node claims to have two 5326// uses while it only has one, use this version, and let isel match 5327// another instruction if the load really happens to have more than 5328// one use. Remove this version after this bug get fixed. 5329// rdar://8434668, PR8156 5330static bool RelaxedMayFoldVectorLoad(SDValue V) { 5331 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 5332 V = V.getOperand(0); 5333 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 5334 V = V.getOperand(0); 5335 if (ISD::isNormalLoad(V.getNode())) 5336 return true; 5337 return false; 5338} 5339 5340/// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by 5341/// a vector extract, and if both can be later optimized into a single load. 5342/// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked 5343/// here because otherwise a target specific shuffle node is going to be 5344/// emitted for this shuffle, and the optimization not done. 5345/// FIXME: This is probably not the best approach, but fix the problem 5346/// until the right path is decided. 5347static 5348bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG, 5349 const TargetLowering &TLI) { 5350 EVT VT = V.getValueType(); 5351 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V); 5352 5353 // Be sure that the vector shuffle is present in a pattern like this: 5354 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr) 5355 if (!V.hasOneUse()) 5356 return false; 5357 5358 SDNode *N = *V.getNode()->use_begin(); 5359 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 5360 return false; 5361 5362 SDValue EltNo = N->getOperand(1); 5363 if (!isa<ConstantSDNode>(EltNo)) 5364 return false; 5365 5366 // If the bit convert changed the number of elements, it is unsafe 5367 // to examine the mask. 5368 bool HasShuffleIntoBitcast = false; 5369 if (V.getOpcode() == ISD::BITCAST) { 5370 EVT SrcVT = V.getOperand(0).getValueType(); 5371 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements()) 5372 return false; 5373 V = V.getOperand(0); 5374 HasShuffleIntoBitcast = true; 5375 } 5376 5377 // Select the input vector, guarding against out of range extract vector. 5378 unsigned NumElems = VT.getVectorNumElements(); 5379 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5380 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt); 5381 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1); 5382 5383 // Skip one more bit_convert if necessary 5384 if (V.getOpcode() == ISD::BITCAST) 5385 V = V.getOperand(0); 5386 5387 if (ISD::isNormalLoad(V.getNode())) { 5388 // Is the original load suitable? 5389 LoadSDNode *LN0 = cast<LoadSDNode>(V); 5390 5391 // FIXME: avoid the multi-use bug that is preventing lots of 5392 // of foldings to be detected, this is still wrong of course, but 5393 // give the temporary desired behavior, and if it happens that 5394 // the load has real more uses, during isel it will not fold, and 5395 // will generate poor code. 5396 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse() 5397 return false; 5398 5399 if (!HasShuffleIntoBitcast) 5400 return true; 5401 5402 // If there's a bitcast before the shuffle, check if the load type and 5403 // alignment is valid. 5404 unsigned Align = LN0->getAlignment(); 5405 unsigned NewAlign = 5406 TLI.getTargetData()->getABITypeAlignment( 5407 VT.getTypeForEVT(*DAG.getContext())); 5408 5409 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT)) 5410 return false; 5411 } 5412 5413 return true; 5414} 5415 5416static 5417SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) { 5418 EVT VT = Op.getValueType(); 5419 5420 // Canonizalize to v2f64. 5421 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 5422 return DAG.getNode(ISD::BITCAST, dl, VT, 5423 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64, 5424 V1, DAG)); 5425} 5426 5427static 5428SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, 5429 bool HasSSE2) { 5430 SDValue V1 = Op.getOperand(0); 5431 SDValue V2 = Op.getOperand(1); 5432 EVT VT = Op.getValueType(); 5433 5434 assert(VT != MVT::v2i64 && "unsupported shuffle type"); 5435 5436 if (HasSSE2 && VT == MVT::v2f64) 5437 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG); 5438 5439 // v4f32 or v4i32 5440 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG); 5441} 5442 5443static 5444SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) { 5445 SDValue V1 = Op.getOperand(0); 5446 SDValue V2 = Op.getOperand(1); 5447 EVT VT = Op.getValueType(); 5448 5449 assert((VT == MVT::v4i32 || VT == MVT::v4f32) && 5450 "unsupported shuffle type"); 5451 5452 if (V2.getOpcode() == ISD::UNDEF) 5453 V2 = V1; 5454 5455 // v4i32 or v4f32 5456 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG); 5457} 5458 5459static 5460SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) { 5461 SDValue V1 = Op.getOperand(0); 5462 SDValue V2 = Op.getOperand(1); 5463 EVT VT = Op.getValueType(); 5464 unsigned NumElems = VT.getVectorNumElements(); 5465 5466 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second 5467 // operand of these instructions is only memory, so check if there's a 5468 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the 5469 // same masks. 5470 bool CanFoldLoad = false; 5471 5472 // Trivial case, when V2 comes from a load. 5473 if (MayFoldVectorLoad(V2)) 5474 CanFoldLoad = true; 5475 5476 // When V1 is a load, it can be folded later into a store in isel, example: 5477 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1) 5478 // turns into: 5479 // (MOVLPSmr addr:$src1, VR128:$src2) 5480 // So, recognize this potential and also use MOVLPS or MOVLPD 5481 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op)) 5482 CanFoldLoad = true; 5483 5484 // Both of them can't be memory operations though. 5485 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2)) 5486 CanFoldLoad = false; 5487 5488 if (CanFoldLoad) { 5489 if (HasSSE2 && NumElems == 2) 5490 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG); 5491 5492 if (NumElems == 4) 5493 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG); 5494 } 5495 5496 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5497 // movl and movlp will both match v2i64, but v2i64 is never matched by 5498 // movl earlier because we make it strict to avoid messing with the movlp load 5499 // folding logic (see the code above getMOVLP call). Match it here then, 5500 // this is horrible, but will stay like this until we move all shuffle 5501 // matching to x86 specific nodes. Note that for the 1st condition all 5502 // types are matched with movsd. 5503 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp)) 5504 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 5505 else if (HasSSE2) 5506 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 5507 5508 5509 assert(VT != MVT::v4i32 && "unsupported shuffle type"); 5510 5511 // Invert the operand order and use SHUFPS to match it. 5512 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1, 5513 X86::getShuffleSHUFImmediate(SVOp), DAG); 5514} 5515 5516static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) { 5517 switch(VT.getSimpleVT().SimpleTy) { 5518 case MVT::v4i32: return X86ISD::PUNPCKLDQ; 5519 case MVT::v2i64: return X86ISD::PUNPCKLQDQ; 5520 case MVT::v4f32: 5521 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS; 5522 case MVT::v2f64: 5523 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD; 5524 case MVT::v8f32: return X86ISD::VUNPCKLPSY; 5525 case MVT::v4f64: return X86ISD::VUNPCKLPDY; 5526 case MVT::v16i8: return X86ISD::PUNPCKLBW; 5527 case MVT::v8i16: return X86ISD::PUNPCKLWD; 5528 default: 5529 llvm_unreachable("Unknown type for unpckl"); 5530 } 5531 return 0; 5532} 5533 5534static inline unsigned getUNPCKHOpcode(EVT VT) { 5535 switch(VT.getSimpleVT().SimpleTy) { 5536 case MVT::v4i32: return X86ISD::PUNPCKHDQ; 5537 case MVT::v2i64: return X86ISD::PUNPCKHQDQ; 5538 case MVT::v4f32: return X86ISD::UNPCKHPS; 5539 case MVT::v2f64: return X86ISD::UNPCKHPD; 5540 case MVT::v16i8: return X86ISD::PUNPCKHBW; 5541 case MVT::v8i16: return X86ISD::PUNPCKHWD; 5542 default: 5543 llvm_unreachable("Unknown type for unpckh"); 5544 } 5545 return 0; 5546} 5547 5548static 5549SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG, 5550 const TargetLowering &TLI, 5551 const X86Subtarget *Subtarget) { 5552 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5553 EVT VT = Op.getValueType(); 5554 DebugLoc dl = Op.getDebugLoc(); 5555 SDValue V1 = Op.getOperand(0); 5556 SDValue V2 = Op.getOperand(1); 5557 5558 if (isZeroShuffle(SVOp)) 5559 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl); 5560 5561 // Handle splat operations 5562 if (SVOp->isSplat()) { 5563 // Special case, this is the only place now where it's 5564 // allowed to return a vector_shuffle operation without 5565 // using a target specific node, because *hopefully* it 5566 // will be optimized away by the dag combiner. 5567 if (VT.getVectorNumElements() <= 4 && 5568 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI)) 5569 return Op; 5570 5571 // Handle splats by matching through known masks 5572 if (VT.getVectorNumElements() <= 4) 5573 return SDValue(); 5574 5575 // Canonicalize all of the remaining to v4f32. 5576 return PromoteSplat(SVOp, DAG); 5577 } 5578 5579 // If the shuffle can be profitably rewritten as a narrower shuffle, then 5580 // do it! 5581 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 5582 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 5583 if (NewOp.getNode()) 5584 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp); 5585 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) { 5586 // FIXME: Figure out a cleaner way to do this. 5587 // Try to make use of movq to zero out the top part. 5588 if (ISD::isBuildVectorAllZeros(V2.getNode())) { 5589 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 5590 if (NewOp.getNode()) { 5591 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false)) 5592 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0), 5593 DAG, Subtarget, dl); 5594 } 5595 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) { 5596 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 5597 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp))) 5598 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1), 5599 DAG, Subtarget, dl); 5600 } 5601 } 5602 return SDValue(); 5603} 5604 5605SDValue 5606X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { 5607 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5608 SDValue V1 = Op.getOperand(0); 5609 SDValue V2 = Op.getOperand(1); 5610 EVT VT = Op.getValueType(); 5611 DebugLoc dl = Op.getDebugLoc(); 5612 unsigned NumElems = VT.getVectorNumElements(); 5613 bool isMMX = VT.getSizeInBits() == 64; 5614 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF; 5615 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 5616 bool V1IsSplat = false; 5617 bool V2IsSplat = false; 5618 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX(); 5619 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX(); 5620 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX(); 5621 MachineFunction &MF = DAG.getMachineFunction(); 5622 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize); 5623 5624 // Shuffle operations on MMX not supported. 5625 if (isMMX) 5626 return Op; 5627 5628 // Vector shuffle lowering takes 3 steps: 5629 // 5630 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable 5631 // narrowing and commutation of operands should be handled. 5632 // 2) Matching of shuffles with known shuffle masks to x86 target specific 5633 // shuffle nodes. 5634 // 3) Rewriting of unmatched masks into new generic shuffle operations, 5635 // so the shuffle can be broken into other shuffles and the legalizer can 5636 // try the lowering again. 5637 // 5638 // The general ideia is that no vector_shuffle operation should be left to 5639 // be matched during isel, all of them must be converted to a target specific 5640 // node here. 5641 5642 // Normalize the input vectors. Here splats, zeroed vectors, profitable 5643 // narrowing and commutation of operands should be handled. The actual code 5644 // doesn't include all of those, work in progress... 5645 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget); 5646 if (NewOp.getNode()) 5647 return NewOp; 5648 5649 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and 5650 // unpckh_undef). Only use pshufd if speed is more important than size. 5651 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp)) 5652 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5653 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG); 5654 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp)) 5655 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5656 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 5657 5658 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef && 5659 RelaxedMayFoldVectorLoad(V1)) 5660 return getMOVDDup(Op, dl, V1, DAG); 5661 5662 if (X86::isMOVHLPS_v_undef_Mask(SVOp)) 5663 return getMOVHighToLow(Op, dl, DAG); 5664 5665 // Use to match splats 5666 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef && 5667 (VT == MVT::v2f64 || VT == MVT::v2i64)) 5668 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 5669 5670 if (X86::isPSHUFDMask(SVOp)) { 5671 // The actual implementation will match the mask in the if above and then 5672 // during isel it can match several different instructions, not only pshufd 5673 // as its name says, sad but true, emulate the behavior for now... 5674 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64))) 5675 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG); 5676 5677 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp); 5678 5679 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32)) 5680 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG); 5681 5682 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 5683 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1, 5684 TargetMask, DAG); 5685 5686 if (VT == MVT::v4f32) 5687 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1, 5688 TargetMask, DAG); 5689 } 5690 5691 // Check if this can be converted into a logical shift. 5692 bool isLeft = false; 5693 unsigned ShAmt = 0; 5694 SDValue ShVal; 5695 bool isShift = getSubtarget()->hasSSE2() && 5696 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt); 5697 if (isShift && ShVal.hasOneUse()) { 5698 // If the shifted value has multiple uses, it may be cheaper to use 5699 // v_set0 + movlhps or movhlps, etc. 5700 EVT EltVT = VT.getVectorElementType(); 5701 ShAmt *= EltVT.getSizeInBits(); 5702 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 5703 } 5704 5705 if (X86::isMOVLMask(SVOp)) { 5706 if (V1IsUndef) 5707 return V2; 5708 if (ISD::isBuildVectorAllZeros(V1.getNode())) 5709 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl); 5710 if (!X86::isMOVLPMask(SVOp)) { 5711 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 5712 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 5713 5714 if (VT == MVT::v4i32 || VT == MVT::v4f32) 5715 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 5716 } 5717 } 5718 5719 // FIXME: fold these into legal mask. 5720 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp)) 5721 return getMOVLowToHigh(Op, dl, DAG, HasSSE2); 5722 5723 if (X86::isMOVHLPSMask(SVOp)) 5724 return getMOVHighToLow(Op, dl, DAG); 5725 5726 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4) 5727 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG); 5728 5729 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4) 5730 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG); 5731 5732 if (X86::isMOVLPMask(SVOp)) 5733 return getMOVLP(Op, dl, DAG, HasSSE2); 5734 5735 if (ShouldXformToMOVHLPS(SVOp) || 5736 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp)) 5737 return CommuteVectorShuffle(SVOp, DAG); 5738 5739 if (isShift) { 5740 // No better options. Use a vshl / vsrl. 5741 EVT EltVT = VT.getVectorElementType(); 5742 ShAmt *= EltVT.getSizeInBits(); 5743 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 5744 } 5745 5746 bool Commuted = false; 5747 // FIXME: This should also accept a bitcast of a splat? Be careful, not 5748 // 1,1,1,1 -> v8i16 though. 5749 V1IsSplat = isSplatVector(V1.getNode()); 5750 V2IsSplat = isSplatVector(V2.getNode()); 5751 5752 // Canonicalize the splat or undef, if present, to be on the RHS. 5753 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) { 5754 Op = CommuteVectorShuffle(SVOp, DAG); 5755 SVOp = cast<ShuffleVectorSDNode>(Op); 5756 V1 = SVOp->getOperand(0); 5757 V2 = SVOp->getOperand(1); 5758 std::swap(V1IsSplat, V2IsSplat); 5759 std::swap(V1IsUndef, V2IsUndef); 5760 Commuted = true; 5761 } 5762 5763 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) { 5764 // Shuffling low element of v1 into undef, just return v1. 5765 if (V2IsUndef) 5766 return V1; 5767 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which 5768 // the instruction selector will not match, so get a canonical MOVL with 5769 // swapped operands to undo the commute. 5770 return getMOVL(DAG, dl, VT, V2, V1); 5771 } 5772 5773 if (X86::isUNPCKLMask(SVOp)) 5774 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), 5775 dl, VT, V1, V2, DAG); 5776 5777 if (X86::isUNPCKHMask(SVOp)) 5778 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG); 5779 5780 if (V2IsSplat) { 5781 // Normalize mask so all entries that point to V2 points to its first 5782 // element then try to match unpck{h|l} again. If match, return a 5783 // new vector_shuffle with the corrected mask. 5784 SDValue NewMask = NormalizeMask(SVOp, DAG); 5785 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask); 5786 if (NSVOp != SVOp) { 5787 if (X86::isUNPCKLMask(NSVOp, true)) { 5788 return NewMask; 5789 } else if (X86::isUNPCKHMask(NSVOp, true)) { 5790 return NewMask; 5791 } 5792 } 5793 } 5794 5795 if (Commuted) { 5796 // Commute is back and try unpck* again. 5797 // FIXME: this seems wrong. 5798 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG); 5799 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp); 5800 5801 if (X86::isUNPCKLMask(NewSVOp)) 5802 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), 5803 dl, VT, V2, V1, DAG); 5804 5805 if (X86::isUNPCKHMask(NewSVOp)) 5806 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG); 5807 } 5808 5809 // Normalize the node to match x86 shuffle ops if needed 5810 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp)) 5811 return CommuteVectorShuffle(SVOp, DAG); 5812 5813 // The checks below are all present in isShuffleMaskLegal, but they are 5814 // inlined here right now to enable us to directly emit target specific 5815 // nodes, and remove one by one until they don't return Op anymore. 5816 SmallVector<int, 16> M; 5817 SVOp->getMask(M); 5818 5819 if (isPALIGNRMask(M, VT, HasSSSE3)) 5820 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2, 5821 X86::getShufflePALIGNRImmediate(SVOp), 5822 DAG); 5823 5824 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) && 5825 SVOp->getSplatIndex() == 0 && V2IsUndef) { 5826 if (VT == MVT::v2f64) { 5827 X86ISD::NodeType Opcode = 5828 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD; 5829 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG); 5830 } 5831 if (VT == MVT::v2i64) 5832 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG); 5833 } 5834 5835 if (isPSHUFHWMask(M, VT)) 5836 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1, 5837 X86::getShufflePSHUFHWImmediate(SVOp), 5838 DAG); 5839 5840 if (isPSHUFLWMask(M, VT)) 5841 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1, 5842 X86::getShufflePSHUFLWImmediate(SVOp), 5843 DAG); 5844 5845 if (isSHUFPMask(M, VT)) { 5846 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp); 5847 if (VT == MVT::v4f32 || VT == MVT::v4i32) 5848 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2, 5849 TargetMask, DAG); 5850 if (VT == MVT::v2f64 || VT == MVT::v2i64) 5851 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2, 5852 TargetMask, DAG); 5853 } 5854 5855 if (X86::isUNPCKL_v_undef_Mask(SVOp)) 5856 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5857 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), 5858 dl, VT, V1, V1, DAG); 5859 if (X86::isUNPCKH_v_undef_Mask(SVOp)) 5860 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5861 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 5862 5863 // Handle v8i16 specifically since SSE can do byte extraction and insertion. 5864 if (VT == MVT::v8i16) { 5865 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG); 5866 if (NewOp.getNode()) 5867 return NewOp; 5868 } 5869 5870 if (VT == MVT::v16i8) { 5871 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this); 5872 if (NewOp.getNode()) 5873 return NewOp; 5874 } 5875 5876 // Handle all 4 wide cases with a number of shuffles. 5877 if (NumElems == 4) 5878 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG); 5879 5880 return SDValue(); 5881} 5882 5883SDValue 5884X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, 5885 SelectionDAG &DAG) const { 5886 EVT VT = Op.getValueType(); 5887 DebugLoc dl = Op.getDebugLoc(); 5888 if (VT.getSizeInBits() == 8) { 5889 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, 5890 Op.getOperand(0), Op.getOperand(1)); 5891 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 5892 DAG.getValueType(VT)); 5893 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 5894 } else if (VT.getSizeInBits() == 16) { 5895 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 5896 // If Idx is 0, it's cheaper to do a move instead of a pextrw. 5897 if (Idx == 0) 5898 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 5899 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 5900 DAG.getNode(ISD::BITCAST, dl, 5901 MVT::v4i32, 5902 Op.getOperand(0)), 5903 Op.getOperand(1))); 5904 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, 5905 Op.getOperand(0), Op.getOperand(1)); 5906 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 5907 DAG.getValueType(VT)); 5908 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 5909 } else if (VT == MVT::f32) { 5910 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy 5911 // the result back to FR32 register. It's only worth matching if the 5912 // result has a single use which is a store or a bitcast to i32. And in 5913 // the case of a store, it's not worth it if the index is a constant 0, 5914 // because a MOVSSmr can be used instead, which is smaller and faster. 5915 if (!Op.hasOneUse()) 5916 return SDValue(); 5917 SDNode *User = *Op.getNode()->use_begin(); 5918 if ((User->getOpcode() != ISD::STORE || 5919 (isa<ConstantSDNode>(Op.getOperand(1)) && 5920 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) && 5921 (User->getOpcode() != ISD::BITCAST || 5922 User->getValueType(0) != MVT::i32)) 5923 return SDValue(); 5924 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 5925 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, 5926 Op.getOperand(0)), 5927 Op.getOperand(1)); 5928 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract); 5929 } else if (VT == MVT::i32) { 5930 // ExtractPS works with constant index. 5931 if (isa<ConstantSDNode>(Op.getOperand(1))) 5932 return Op; 5933 } 5934 return SDValue(); 5935} 5936 5937 5938SDValue 5939X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 5940 SelectionDAG &DAG) const { 5941 if (!isa<ConstantSDNode>(Op.getOperand(1))) 5942 return SDValue(); 5943 5944 SDValue Vec = Op.getOperand(0); 5945 EVT VecVT = Vec.getValueType(); 5946 5947 // If this is a 256-bit vector result, first extract the 128-bit 5948 // vector and then extract from the 128-bit vector. 5949 if (VecVT.getSizeInBits() > 128) { 5950 DebugLoc dl = Op.getNode()->getDebugLoc(); 5951 unsigned NumElems = VecVT.getVectorNumElements(); 5952 SDValue Idx = Op.getOperand(1); 5953 5954 if (!isa<ConstantSDNode>(Idx)) 5955 return SDValue(); 5956 5957 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128); 5958 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5959 5960 // Get the 128-bit vector. 5961 bool Upper = IdxVal >= ExtractNumElems; 5962 Vec = Extract128BitVector(Vec, Idx, DAG, dl); 5963 5964 // Extract from it. 5965 SDValue ScaledIdx = Idx; 5966 if (Upper) 5967 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx, 5968 DAG.getConstant(ExtractNumElems, 5969 Idx.getValueType())); 5970 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec, 5971 ScaledIdx); 5972 } 5973 5974 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length"); 5975 5976 if (Subtarget->hasSSE41()) { 5977 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG); 5978 if (Res.getNode()) 5979 return Res; 5980 } 5981 5982 EVT VT = Op.getValueType(); 5983 DebugLoc dl = Op.getDebugLoc(); 5984 // TODO: handle v16i8. 5985 if (VT.getSizeInBits() == 16) { 5986 SDValue Vec = Op.getOperand(0); 5987 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 5988 if (Idx == 0) 5989 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 5990 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 5991 DAG.getNode(ISD::BITCAST, dl, 5992 MVT::v4i32, Vec), 5993 Op.getOperand(1))); 5994 // Transform it so it match pextrw which produces a 32-bit result. 5995 EVT EltVT = MVT::i32; 5996 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, 5997 Op.getOperand(0), Op.getOperand(1)); 5998 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract, 5999 DAG.getValueType(VT)); 6000 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6001 } else if (VT.getSizeInBits() == 32) { 6002 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6003 if (Idx == 0) 6004 return Op; 6005 6006 // SHUFPS the element to the lowest double word, then movss. 6007 int Mask[4] = { Idx, -1, -1, -1 }; 6008 EVT VVT = Op.getOperand(0).getValueType(); 6009 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 6010 DAG.getUNDEF(VVT), Mask); 6011 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 6012 DAG.getIntPtrConstant(0)); 6013 } else if (VT.getSizeInBits() == 64) { 6014 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b 6015 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught 6016 // to match extract_elt for f64. 6017 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6018 if (Idx == 0) 6019 return Op; 6020 6021 // UNPCKHPD the element to the lowest double word, then movsd. 6022 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored 6023 // to a f64mem, the whole operation is folded into a single MOVHPDmr. 6024 int Mask[2] = { 1, -1 }; 6025 EVT VVT = Op.getOperand(0).getValueType(); 6026 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 6027 DAG.getUNDEF(VVT), Mask); 6028 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 6029 DAG.getIntPtrConstant(0)); 6030 } 6031 6032 return SDValue(); 6033} 6034 6035SDValue 6036X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, 6037 SelectionDAG &DAG) const { 6038 EVT VT = Op.getValueType(); 6039 EVT EltVT = VT.getVectorElementType(); 6040 DebugLoc dl = Op.getDebugLoc(); 6041 6042 SDValue N0 = Op.getOperand(0); 6043 SDValue N1 = Op.getOperand(1); 6044 SDValue N2 = Op.getOperand(2); 6045 6046 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) && 6047 isa<ConstantSDNode>(N2)) { 6048 unsigned Opc; 6049 if (VT == MVT::v8i16) 6050 Opc = X86ISD::PINSRW; 6051 else if (VT == MVT::v16i8) 6052 Opc = X86ISD::PINSRB; 6053 else 6054 Opc = X86ISD::PINSRB; 6055 6056 // Transform it so it match pinsr{b,w} which expects a GR32 as its second 6057 // argument. 6058 if (N1.getValueType() != MVT::i32) 6059 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 6060 if (N2.getValueType() != MVT::i32) 6061 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 6062 return DAG.getNode(Opc, dl, VT, N0, N1, N2); 6063 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) { 6064 // Bits [7:6] of the constant are the source select. This will always be 6065 // zero here. The DAG Combiner may combine an extract_elt index into these 6066 // bits. For example (insert (extract, 3), 2) could be matched by putting 6067 // the '3' into bits [7:6] of X86ISD::INSERTPS. 6068 // Bits [5:4] of the constant are the destination select. This is the 6069 // value of the incoming immediate. 6070 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may 6071 // combine either bitwise AND or insert of float 0.0 to set these bits. 6072 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4); 6073 // Create this as a scalar to vector.. 6074 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1); 6075 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2); 6076 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) { 6077 // PINSR* works with constant index. 6078 return Op; 6079 } 6080 return SDValue(); 6081} 6082 6083SDValue 6084X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 6085 EVT VT = Op.getValueType(); 6086 EVT EltVT = VT.getVectorElementType(); 6087 6088 DebugLoc dl = Op.getDebugLoc(); 6089 SDValue N0 = Op.getOperand(0); 6090 SDValue N1 = Op.getOperand(1); 6091 SDValue N2 = Op.getOperand(2); 6092 6093 // If this is a 256-bit vector result, first insert into a 128-bit 6094 // vector and then insert into the 256-bit vector. 6095 if (VT.getSizeInBits() > 128) { 6096 if (!isa<ConstantSDNode>(N2)) 6097 return SDValue(); 6098 6099 // Get the 128-bit vector. 6100 unsigned NumElems = VT.getVectorNumElements(); 6101 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue(); 6102 bool Upper = IdxVal >= NumElems / 2; 6103 6104 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl); 6105 6106 // Insert into it. 6107 SDValue ScaledN2 = N2; 6108 if (Upper) 6109 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2, 6110 DAG.getConstant(NumElems / 6111 (VT.getSizeInBits() / 128), 6112 N2.getValueType())); 6113 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0, 6114 N1, ScaledN2); 6115 6116 // Insert the 128-bit vector 6117 // FIXME: Why UNDEF? 6118 return Insert128BitVector(N0, Op, N2, DAG, dl); 6119 } 6120 6121 if (Subtarget->hasSSE41()) 6122 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG); 6123 6124 if (EltVT == MVT::i8) 6125 return SDValue(); 6126 6127 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) { 6128 // Transform it so it match pinsrw which expects a 16-bit value in a GR32 6129 // as its second argument. 6130 if (N1.getValueType() != MVT::i32) 6131 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 6132 if (N2.getValueType() != MVT::i32) 6133 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 6134 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2); 6135 } 6136 return SDValue(); 6137} 6138 6139SDValue 6140X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const { 6141 LLVMContext *Context = DAG.getContext(); 6142 DebugLoc dl = Op.getDebugLoc(); 6143 EVT OpVT = Op.getValueType(); 6144 6145 // If this is a 256-bit vector result, first insert into a 128-bit 6146 // vector and then insert into the 256-bit vector. 6147 if (OpVT.getSizeInBits() > 128) { 6148 // Insert into a 128-bit vector. 6149 EVT VT128 = EVT::getVectorVT(*Context, 6150 OpVT.getVectorElementType(), 6151 OpVT.getVectorNumElements() / 2); 6152 6153 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0)); 6154 6155 // Insert the 128-bit vector. 6156 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op, 6157 DAG.getConstant(0, MVT::i32), 6158 DAG, dl); 6159 } 6160 6161 if (Op.getValueType() == MVT::v1i64 && 6162 Op.getOperand(0).getValueType() == MVT::i64) 6163 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0)); 6164 6165 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0)); 6166 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 && 6167 "Expected an SSE type!"); 6168 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), 6169 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt)); 6170} 6171 6172// Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in 6173// a simple subregister reference or explicit instructions to grab 6174// upper bits of a vector. 6175SDValue 6176X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 6177 if (Subtarget->hasAVX()) { 6178 DebugLoc dl = Op.getNode()->getDebugLoc(); 6179 SDValue Vec = Op.getNode()->getOperand(0); 6180 SDValue Idx = Op.getNode()->getOperand(1); 6181 6182 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 6183 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) { 6184 return Extract128BitVector(Vec, Idx, DAG, dl); 6185 } 6186 } 6187 return SDValue(); 6188} 6189 6190// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a 6191// simple superregister reference or explicit instructions to insert 6192// the upper bits of a vector. 6193SDValue 6194X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 6195 if (Subtarget->hasAVX()) { 6196 DebugLoc dl = Op.getNode()->getDebugLoc(); 6197 SDValue Vec = Op.getNode()->getOperand(0); 6198 SDValue SubVec = Op.getNode()->getOperand(1); 6199 SDValue Idx = Op.getNode()->getOperand(2); 6200 6201 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 6202 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) { 6203 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl); 6204 } 6205 } 6206 return SDValue(); 6207} 6208 6209// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 6210// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is 6211// one of the above mentioned nodes. It has to be wrapped because otherwise 6212// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 6213// be used to form addressing mode. These wrapped nodes will be selected 6214// into MOV32ri. 6215SDValue 6216X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { 6217 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 6218 6219 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6220 // global base reg. 6221 unsigned char OpFlag = 0; 6222 unsigned WrapperKind = X86ISD::Wrapper; 6223 CodeModel::Model M = getTargetMachine().getCodeModel(); 6224 6225 if (Subtarget->isPICStyleRIPRel() && 6226 (M == CodeModel::Small || M == CodeModel::Kernel)) 6227 WrapperKind = X86ISD::WrapperRIP; 6228 else if (Subtarget->isPICStyleGOT()) 6229 OpFlag = X86II::MO_GOTOFF; 6230 else if (Subtarget->isPICStyleStubPIC()) 6231 OpFlag = X86II::MO_PIC_BASE_OFFSET; 6232 6233 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(), 6234 CP->getAlignment(), 6235 CP->getOffset(), OpFlag); 6236 DebugLoc DL = CP->getDebugLoc(); 6237 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6238 // With PIC, the address is actually $g + Offset. 6239 if (OpFlag) { 6240 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6241 DAG.getNode(X86ISD::GlobalBaseReg, 6242 DebugLoc(), getPointerTy()), 6243 Result); 6244 } 6245 6246 return Result; 6247} 6248 6249SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 6250 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 6251 6252 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6253 // global base reg. 6254 unsigned char OpFlag = 0; 6255 unsigned WrapperKind = X86ISD::Wrapper; 6256 CodeModel::Model M = getTargetMachine().getCodeModel(); 6257 6258 if (Subtarget->isPICStyleRIPRel() && 6259 (M == CodeModel::Small || M == CodeModel::Kernel)) 6260 WrapperKind = X86ISD::WrapperRIP; 6261 else if (Subtarget->isPICStyleGOT()) 6262 OpFlag = X86II::MO_GOTOFF; 6263 else if (Subtarget->isPICStyleStubPIC()) 6264 OpFlag = X86II::MO_PIC_BASE_OFFSET; 6265 6266 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(), 6267 OpFlag); 6268 DebugLoc DL = JT->getDebugLoc(); 6269 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6270 6271 // With PIC, the address is actually $g + Offset. 6272 if (OpFlag) 6273 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6274 DAG.getNode(X86ISD::GlobalBaseReg, 6275 DebugLoc(), getPointerTy()), 6276 Result); 6277 6278 return Result; 6279} 6280 6281SDValue 6282X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { 6283 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 6284 6285 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6286 // global base reg. 6287 unsigned char OpFlag = 0; 6288 unsigned WrapperKind = X86ISD::Wrapper; 6289 CodeModel::Model M = getTargetMachine().getCodeModel(); 6290 6291 if (Subtarget->isPICStyleRIPRel() && 6292 (M == CodeModel::Small || M == CodeModel::Kernel)) 6293 WrapperKind = X86ISD::WrapperRIP; 6294 else if (Subtarget->isPICStyleGOT()) 6295 OpFlag = X86II::MO_GOTOFF; 6296 else if (Subtarget->isPICStyleStubPIC()) 6297 OpFlag = X86II::MO_PIC_BASE_OFFSET; 6298 6299 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag); 6300 6301 DebugLoc DL = Op.getDebugLoc(); 6302 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6303 6304 6305 // With PIC, the address is actually $g + Offset. 6306 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 6307 !Subtarget->is64Bit()) { 6308 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6309 DAG.getNode(X86ISD::GlobalBaseReg, 6310 DebugLoc(), getPointerTy()), 6311 Result); 6312 } 6313 6314 return Result; 6315} 6316 6317SDValue 6318X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { 6319 // Create the TargetBlockAddressAddress node. 6320 unsigned char OpFlags = 6321 Subtarget->ClassifyBlockAddressReference(); 6322 CodeModel::Model M = getTargetMachine().getCodeModel(); 6323 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 6324 DebugLoc dl = Op.getDebugLoc(); 6325 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), 6326 /*isTarget=*/true, OpFlags); 6327 6328 if (Subtarget->isPICStyleRIPRel() && 6329 (M == CodeModel::Small || M == CodeModel::Kernel)) 6330 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 6331 else 6332 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 6333 6334 // With PIC, the address is actually $g + Offset. 6335 if (isGlobalRelativeToPICBase(OpFlags)) { 6336 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 6337 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 6338 Result); 6339 } 6340 6341 return Result; 6342} 6343 6344SDValue 6345X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl, 6346 int64_t Offset, 6347 SelectionDAG &DAG) const { 6348 // Create the TargetGlobalAddress node, folding in the constant 6349 // offset if it is legal. 6350 unsigned char OpFlags = 6351 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 6352 CodeModel::Model M = getTargetMachine().getCodeModel(); 6353 SDValue Result; 6354 if (OpFlags == X86II::MO_NO_FLAG && 6355 X86::isOffsetSuitableForCodeModel(Offset, M)) { 6356 // A direct static reference to a global. 6357 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset); 6358 Offset = 0; 6359 } else { 6360 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 6361 } 6362 6363 if (Subtarget->isPICStyleRIPRel() && 6364 (M == CodeModel::Small || M == CodeModel::Kernel)) 6365 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 6366 else 6367 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 6368 6369 // With PIC, the address is actually $g + Offset. 6370 if (isGlobalRelativeToPICBase(OpFlags)) { 6371 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 6372 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 6373 Result); 6374 } 6375 6376 // For globals that require a load from a stub to get the address, emit the 6377 // load. 6378 if (isGlobalStubReference(OpFlags)) 6379 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result, 6380 MachinePointerInfo::getGOT(), false, false, 0); 6381 6382 // If there was a non-zero offset that we didn't fold, create an explicit 6383 // addition for it. 6384 if (Offset != 0) 6385 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result, 6386 DAG.getConstant(Offset, getPointerTy())); 6387 6388 return Result; 6389} 6390 6391SDValue 6392X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { 6393 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 6394 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 6395 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG); 6396} 6397 6398static SDValue 6399GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, 6400 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg, 6401 unsigned char OperandFlags) { 6402 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 6403 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6404 DebugLoc dl = GA->getDebugLoc(); 6405 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 6406 GA->getValueType(0), 6407 GA->getOffset(), 6408 OperandFlags); 6409 if (InFlag) { 6410 SDValue Ops[] = { Chain, TGA, *InFlag }; 6411 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3); 6412 } else { 6413 SDValue Ops[] = { Chain, TGA }; 6414 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2); 6415 } 6416 6417 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 6418 MFI->setAdjustsStack(true); 6419 6420 SDValue Flag = Chain.getValue(1); 6421 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag); 6422} 6423 6424// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit 6425static SDValue 6426LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG, 6427 const EVT PtrVT) { 6428 SDValue InFlag; 6429 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better 6430 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 6431 DAG.getNode(X86ISD::GlobalBaseReg, 6432 DebugLoc(), PtrVT), InFlag); 6433 InFlag = Chain.getValue(1); 6434 6435 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD); 6436} 6437 6438// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit 6439static SDValue 6440LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG, 6441 const EVT PtrVT) { 6442 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, 6443 X86::RAX, X86II::MO_TLSGD); 6444} 6445 6446// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or 6447// "local exec" model. 6448static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG, 6449 const EVT PtrVT, TLSModel::Model model, 6450 bool is64Bit) { 6451 DebugLoc dl = GA->getDebugLoc(); 6452 6453 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit). 6454 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(), 6455 is64Bit ? 257 : 256)); 6456 6457 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 6458 DAG.getIntPtrConstant(0), 6459 MachinePointerInfo(Ptr), false, false, 0); 6460 6461 unsigned char OperandFlags = 0; 6462 // Most TLS accesses are not RIP relative, even on x86-64. One exception is 6463 // initialexec. 6464 unsigned WrapperKind = X86ISD::Wrapper; 6465 if (model == TLSModel::LocalExec) { 6466 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF; 6467 } else if (is64Bit) { 6468 assert(model == TLSModel::InitialExec); 6469 OperandFlags = X86II::MO_GOTTPOFF; 6470 WrapperKind = X86ISD::WrapperRIP; 6471 } else { 6472 assert(model == TLSModel::InitialExec); 6473 OperandFlags = X86II::MO_INDNTPOFF; 6474 } 6475 6476 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial 6477 // exec) 6478 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 6479 GA->getValueType(0), 6480 GA->getOffset(), OperandFlags); 6481 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 6482 6483 if (model == TLSModel::InitialExec) 6484 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset, 6485 MachinePointerInfo::getGOT(), false, false, 0); 6486 6487 // The address of the thread local variable is the add of the thread 6488 // pointer with the offset of the variable. 6489 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 6490} 6491 6492SDValue 6493X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 6494 6495 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6496 const GlobalValue *GV = GA->getGlobal(); 6497 6498 if (Subtarget->isTargetELF()) { 6499 // TODO: implement the "local dynamic" model 6500 // TODO: implement the "initial exec"model for pic executables 6501 6502 // If GV is an alias then use the aliasee for determining 6503 // thread-localness. 6504 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 6505 GV = GA->resolveAliasedGlobal(false); 6506 6507 TLSModel::Model model 6508 = getTLSModel(GV, getTargetMachine().getRelocationModel()); 6509 6510 switch (model) { 6511 case TLSModel::GeneralDynamic: 6512 case TLSModel::LocalDynamic: // not implemented 6513 if (Subtarget->is64Bit()) 6514 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy()); 6515 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy()); 6516 6517 case TLSModel::InitialExec: 6518 case TLSModel::LocalExec: 6519 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, 6520 Subtarget->is64Bit()); 6521 } 6522 } else if (Subtarget->isTargetDarwin()) { 6523 // Darwin only has one model of TLS. Lower to that. 6524 unsigned char OpFlag = 0; 6525 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ? 6526 X86ISD::WrapperRIP : X86ISD::Wrapper; 6527 6528 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6529 // global base reg. 6530 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) && 6531 !Subtarget->is64Bit(); 6532 if (PIC32) 6533 OpFlag = X86II::MO_TLVP_PIC_BASE; 6534 else 6535 OpFlag = X86II::MO_TLVP; 6536 DebugLoc DL = Op.getDebugLoc(); 6537 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 6538 GA->getValueType(0), 6539 GA->getOffset(), OpFlag); 6540 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6541 6542 // With PIC32, the address is actually $g + Offset. 6543 if (PIC32) 6544 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6545 DAG.getNode(X86ISD::GlobalBaseReg, 6546 DebugLoc(), getPointerTy()), 6547 Offset); 6548 6549 // Lowering the machine isd will make sure everything is in the right 6550 // location. 6551 SDValue Chain = DAG.getEntryNode(); 6552 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6553 SDValue Args[] = { Chain, Offset }; 6554 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2); 6555 6556 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls. 6557 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 6558 MFI->setAdjustsStack(true); 6559 6560 // And our return value (tls address) is in the standard call return value 6561 // location. 6562 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 6563 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy()); 6564 } 6565 6566 assert(false && 6567 "TLS not implemented for this target."); 6568 6569 llvm_unreachable("Unreachable"); 6570 return SDValue(); 6571} 6572 6573 6574/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and 6575/// take a 2 x i32 value to shift plus a shift amount. 6576SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const { 6577 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6578 EVT VT = Op.getValueType(); 6579 unsigned VTBits = VT.getSizeInBits(); 6580 DebugLoc dl = Op.getDebugLoc(); 6581 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS; 6582 SDValue ShOpLo = Op.getOperand(0); 6583 SDValue ShOpHi = Op.getOperand(1); 6584 SDValue ShAmt = Op.getOperand(2); 6585 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 6586 DAG.getConstant(VTBits - 1, MVT::i8)) 6587 : DAG.getConstant(0, VT); 6588 6589 SDValue Tmp2, Tmp3; 6590 if (Op.getOpcode() == ISD::SHL_PARTS) { 6591 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt); 6592 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6593 } else { 6594 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt); 6595 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt); 6596 } 6597 6598 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt, 6599 DAG.getConstant(VTBits, MVT::i8)); 6600 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 6601 AndNode, DAG.getConstant(0, MVT::i8)); 6602 6603 SDValue Hi, Lo; 6604 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8); 6605 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond }; 6606 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond }; 6607 6608 if (Op.getOpcode() == ISD::SHL_PARTS) { 6609 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 6610 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 6611 } else { 6612 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 6613 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 6614 } 6615 6616 SDValue Ops[2] = { Lo, Hi }; 6617 return DAG.getMergeValues(Ops, 2, dl); 6618} 6619 6620SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, 6621 SelectionDAG &DAG) const { 6622 EVT SrcVT = Op.getOperand(0).getValueType(); 6623 6624 if (SrcVT.isVector()) 6625 return SDValue(); 6626 6627 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 && 6628 "Unknown SINT_TO_FP to lower!"); 6629 6630 // These are really Legal; return the operand so the caller accepts it as 6631 // Legal. 6632 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType())) 6633 return Op; 6634 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) && 6635 Subtarget->is64Bit()) { 6636 return Op; 6637 } 6638 6639 DebugLoc dl = Op.getDebugLoc(); 6640 unsigned Size = SrcVT.getSizeInBits()/8; 6641 MachineFunction &MF = DAG.getMachineFunction(); 6642 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false); 6643 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 6644 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 6645 StackSlot, 6646 MachinePointerInfo::getFixedStack(SSFI), 6647 false, false, 0); 6648 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG); 6649} 6650 6651SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain, 6652 SDValue StackSlot, 6653 SelectionDAG &DAG) const { 6654 // Build the FILD 6655 DebugLoc DL = Op.getDebugLoc(); 6656 SDVTList Tys; 6657 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType()); 6658 if (useSSE) 6659 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue); 6660 else 6661 Tys = DAG.getVTList(Op.getValueType(), MVT::Other); 6662 6663 unsigned ByteSize = SrcVT.getSizeInBits()/8; 6664 6665 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 6666 MachineMemOperand *MMO = 6667 DAG.getMachineFunction() 6668 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6669 MachineMemOperand::MOLoad, ByteSize, ByteSize); 6670 6671 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; 6672 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : 6673 X86ISD::FILD, DL, 6674 Tys, Ops, array_lengthof(Ops), 6675 SrcVT, MMO); 6676 6677 if (useSSE) { 6678 Chain = Result.getValue(1); 6679 SDValue InFlag = Result.getValue(2); 6680 6681 // FIXME: Currently the FST is flagged to the FILD_FLAG. This 6682 // shouldn't be necessary except that RFP cannot be live across 6683 // multiple blocks. When stackifier is fixed, they can be uncoupled. 6684 MachineFunction &MF = DAG.getMachineFunction(); 6685 unsigned SSFISize = Op.getValueType().getSizeInBits()/8; 6686 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false); 6687 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 6688 Tys = DAG.getVTList(MVT::Other); 6689 SDValue Ops[] = { 6690 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag 6691 }; 6692 MachineMemOperand *MMO = 6693 DAG.getMachineFunction() 6694 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6695 MachineMemOperand::MOStore, SSFISize, SSFISize); 6696 6697 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, 6698 Ops, array_lengthof(Ops), 6699 Op.getValueType(), MMO); 6700 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot, 6701 MachinePointerInfo::getFixedStack(SSFI), 6702 false, false, 0); 6703 } 6704 6705 return Result; 6706} 6707 6708// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion. 6709SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, 6710 SelectionDAG &DAG) const { 6711 // This algorithm is not obvious. Here it is in C code, more or less: 6712 /* 6713 double uint64_to_double( uint32_t hi, uint32_t lo ) { 6714 static const __m128i exp = { 0x4330000045300000ULL, 0 }; 6715 static const __m128d bias = { 0x1.0p84, 0x1.0p52 }; 6716 6717 // Copy ints to xmm registers. 6718 __m128i xh = _mm_cvtsi32_si128( hi ); 6719 __m128i xl = _mm_cvtsi32_si128( lo ); 6720 6721 // Combine into low half of a single xmm register. 6722 __m128i x = _mm_unpacklo_epi32( xh, xl ); 6723 __m128d d; 6724 double sd; 6725 6726 // Merge in appropriate exponents to give the integer bits the right 6727 // magnitude. 6728 x = _mm_unpacklo_epi32( x, exp ); 6729 6730 // Subtract away the biases to deal with the IEEE-754 double precision 6731 // implicit 1. 6732 d = _mm_sub_pd( (__m128d) x, bias ); 6733 6734 // All conversions up to here are exact. The correctly rounded result is 6735 // calculated using the current rounding mode using the following 6736 // horizontal add. 6737 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) ); 6738 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this 6739 // store doesn't really need to be here (except 6740 // maybe to zero the other double) 6741 return sd; 6742 } 6743 */ 6744 6745 DebugLoc dl = Op.getDebugLoc(); 6746 LLVMContext *Context = DAG.getContext(); 6747 6748 // Build some magic constants. 6749 std::vector<Constant*> CV0; 6750 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000))); 6751 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000))); 6752 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 6753 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 6754 Constant *C0 = ConstantVector::get(CV0); 6755 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16); 6756 6757 std::vector<Constant*> CV1; 6758 CV1.push_back( 6759 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL)))); 6760 CV1.push_back( 6761 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL)))); 6762 Constant *C1 = ConstantVector::get(CV1); 6763 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16); 6764 6765 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 6766 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 6767 Op.getOperand(0), 6768 DAG.getIntPtrConstant(1))); 6769 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 6770 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 6771 Op.getOperand(0), 6772 DAG.getIntPtrConstant(0))); 6773 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2); 6774 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0, 6775 MachinePointerInfo::getConstantPool(), 6776 false, false, 16); 6777 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0); 6778 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2); 6779 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1, 6780 MachinePointerInfo::getConstantPool(), 6781 false, false, 16); 6782 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1); 6783 6784 // Add the halves; easiest way is to swap them into another reg first. 6785 int ShufMask[2] = { 1, -1 }; 6786 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, 6787 DAG.getUNDEF(MVT::v2f64), ShufMask); 6788 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub); 6789 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add, 6790 DAG.getIntPtrConstant(0)); 6791} 6792 6793// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion. 6794SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, 6795 SelectionDAG &DAG) const { 6796 DebugLoc dl = Op.getDebugLoc(); 6797 // FP constant to bias correct the final result. 6798 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 6799 MVT::f64); 6800 6801 // Load the 32-bit value into an XMM register. 6802 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 6803 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 6804 Op.getOperand(0), 6805 DAG.getIntPtrConstant(0))); 6806 6807 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 6808 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load), 6809 DAG.getIntPtrConstant(0)); 6810 6811 // Or the load with the bias. 6812 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, 6813 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 6814 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6815 MVT::v2f64, Load)), 6816 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 6817 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6818 MVT::v2f64, Bias))); 6819 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 6820 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or), 6821 DAG.getIntPtrConstant(0)); 6822 6823 // Subtract the bias. 6824 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias); 6825 6826 // Handle final rounding. 6827 EVT DestVT = Op.getValueType(); 6828 6829 if (DestVT.bitsLT(MVT::f64)) { 6830 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 6831 DAG.getIntPtrConstant(0)); 6832 } else if (DestVT.bitsGT(MVT::f64)) { 6833 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 6834 } 6835 6836 // Handle final rounding. 6837 return Sub; 6838} 6839 6840SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, 6841 SelectionDAG &DAG) const { 6842 SDValue N0 = Op.getOperand(0); 6843 DebugLoc dl = Op.getDebugLoc(); 6844 6845 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't 6846 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform 6847 // the optimization here. 6848 if (DAG.SignBitIsZero(N0)) 6849 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0); 6850 6851 EVT SrcVT = N0.getValueType(); 6852 EVT DstVT = Op.getValueType(); 6853 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64) 6854 return LowerUINT_TO_FP_i64(Op, DAG); 6855 else if (SrcVT == MVT::i32 && X86ScalarSSEf64) 6856 return LowerUINT_TO_FP_i32(Op, DAG); 6857 6858 // Make a 64-bit buffer, and use it to build an FILD. 6859 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64); 6860 if (SrcVT == MVT::i32) { 6861 SDValue WordOff = DAG.getConstant(4, getPointerTy()); 6862 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, 6863 getPointerTy(), StackSlot, WordOff); 6864 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 6865 StackSlot, MachinePointerInfo(), 6866 false, false, 0); 6867 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32), 6868 OffsetSlot, MachinePointerInfo(), 6869 false, false, 0); 6870 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG); 6871 return Fild; 6872 } 6873 6874 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"); 6875 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 6876 StackSlot, MachinePointerInfo(), 6877 false, false, 0); 6878 // For i64 source, we need to add the appropriate power of 2 if the input 6879 // was negative. This is the same as the optimization in 6880 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here, 6881 // we must be careful to do the computation in x87 extended precision, not 6882 // in SSE. (The generic code can't know it's OK to do this, or how to.) 6883 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 6884 MachineMemOperand *MMO = 6885 DAG.getMachineFunction() 6886 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6887 MachineMemOperand::MOLoad, 8, 8); 6888 6889 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other); 6890 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) }; 6891 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3, 6892 MVT::i64, MMO); 6893 6894 APInt FF(32, 0x5F800000ULL); 6895 6896 // Check whether the sign bit is set. 6897 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), 6898 Op.getOperand(0), DAG.getConstant(0, MVT::i64), 6899 ISD::SETLT); 6900 6901 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits. 6902 SDValue FudgePtr = DAG.getConstantPool( 6903 ConstantInt::get(*DAG.getContext(), FF.zext(64)), 6904 getPointerTy()); 6905 6906 // Get a pointer to FF if the sign bit was set, or to 0 otherwise. 6907 SDValue Zero = DAG.getIntPtrConstant(0); 6908 SDValue Four = DAG.getIntPtrConstant(4); 6909 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, 6910 Zero, Four); 6911 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset); 6912 6913 // Load the value out, extending it from f32 to f80. 6914 // FIXME: Avoid the extend by constructing the right constant pool? 6915 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), 6916 FudgePtr, MachinePointerInfo::getConstantPool(), 6917 MVT::f32, false, false, 4); 6918 // Extend everything to 80 bits to force it to be done on x87. 6919 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge); 6920 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0)); 6921} 6922 6923std::pair<SDValue,SDValue> X86TargetLowering:: 6924FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const { 6925 DebugLoc DL = Op.getDebugLoc(); 6926 6927 EVT DstTy = Op.getValueType(); 6928 6929 if (!IsSigned) { 6930 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT"); 6931 DstTy = MVT::i64; 6932 } 6933 6934 assert(DstTy.getSimpleVT() <= MVT::i64 && 6935 DstTy.getSimpleVT() >= MVT::i16 && 6936 "Unknown FP_TO_SINT to lower!"); 6937 6938 // These are really Legal. 6939 if (DstTy == MVT::i32 && 6940 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 6941 return std::make_pair(SDValue(), SDValue()); 6942 if (Subtarget->is64Bit() && 6943 DstTy == MVT::i64 && 6944 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 6945 return std::make_pair(SDValue(), SDValue()); 6946 6947 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary 6948 // stack slot. 6949 MachineFunction &MF = DAG.getMachineFunction(); 6950 unsigned MemSize = DstTy.getSizeInBits()/8; 6951 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 6952 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 6953 6954 6955 6956 unsigned Opc; 6957 switch (DstTy.getSimpleVT().SimpleTy) { 6958 default: llvm_unreachable("Invalid FP_TO_SINT to lower!"); 6959 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break; 6960 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break; 6961 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break; 6962 } 6963 6964 SDValue Chain = DAG.getEntryNode(); 6965 SDValue Value = Op.getOperand(0); 6966 EVT TheVT = Op.getOperand(0).getValueType(); 6967 if (isScalarFPTypeInSSEReg(TheVT)) { 6968 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"); 6969 Chain = DAG.getStore(Chain, DL, Value, StackSlot, 6970 MachinePointerInfo::getFixedStack(SSFI), 6971 false, false, 0); 6972 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other); 6973 SDValue Ops[] = { 6974 Chain, StackSlot, DAG.getValueType(TheVT) 6975 }; 6976 6977 MachineMemOperand *MMO = 6978 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6979 MachineMemOperand::MOLoad, MemSize, MemSize); 6980 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3, 6981 DstTy, MMO); 6982 Chain = Value.getValue(1); 6983 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 6984 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 6985 } 6986 6987 MachineMemOperand *MMO = 6988 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6989 MachineMemOperand::MOStore, MemSize, MemSize); 6990 6991 // Build the FP_TO_INT*_IN_MEM 6992 SDValue Ops[] = { Chain, Value, StackSlot }; 6993 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other), 6994 Ops, 3, DstTy, MMO); 6995 6996 return std::make_pair(FIST, StackSlot); 6997} 6998 6999SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, 7000 SelectionDAG &DAG) const { 7001 if (Op.getValueType().isVector()) 7002 return SDValue(); 7003 7004 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true); 7005 SDValue FIST = Vals.first, StackSlot = Vals.second; 7006 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal. 7007 if (FIST.getNode() == 0) return Op; 7008 7009 // Load the result. 7010 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 7011 FIST, StackSlot, MachinePointerInfo(), false, false, 0); 7012} 7013 7014SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, 7015 SelectionDAG &DAG) const { 7016 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false); 7017 SDValue FIST = Vals.first, StackSlot = Vals.second; 7018 assert(FIST.getNode() && "Unexpected failure"); 7019 7020 // Load the result. 7021 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 7022 FIST, StackSlot, MachinePointerInfo(), false, false, 0); 7023} 7024 7025SDValue X86TargetLowering::LowerFABS(SDValue Op, 7026 SelectionDAG &DAG) const { 7027 LLVMContext *Context = DAG.getContext(); 7028 DebugLoc dl = Op.getDebugLoc(); 7029 EVT VT = Op.getValueType(); 7030 EVT EltVT = VT; 7031 if (VT.isVector()) 7032 EltVT = VT.getVectorElementType(); 7033 std::vector<Constant*> CV; 7034 if (EltVT == MVT::f64) { 7035 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))); 7036 CV.push_back(C); 7037 CV.push_back(C); 7038 } else { 7039 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))); 7040 CV.push_back(C); 7041 CV.push_back(C); 7042 CV.push_back(C); 7043 CV.push_back(C); 7044 } 7045 Constant *C = ConstantVector::get(CV); 7046 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7047 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 7048 MachinePointerInfo::getConstantPool(), 7049 false, false, 16); 7050 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask); 7051} 7052 7053SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const { 7054 LLVMContext *Context = DAG.getContext(); 7055 DebugLoc dl = Op.getDebugLoc(); 7056 EVT VT = Op.getValueType(); 7057 EVT EltVT = VT; 7058 if (VT.isVector()) 7059 EltVT = VT.getVectorElementType(); 7060 std::vector<Constant*> CV; 7061 if (EltVT == MVT::f64) { 7062 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))); 7063 CV.push_back(C); 7064 CV.push_back(C); 7065 } else { 7066 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))); 7067 CV.push_back(C); 7068 CV.push_back(C); 7069 CV.push_back(C); 7070 CV.push_back(C); 7071 } 7072 Constant *C = ConstantVector::get(CV); 7073 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7074 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 7075 MachinePointerInfo::getConstantPool(), 7076 false, false, 16); 7077 if (VT.isVector()) { 7078 return DAG.getNode(ISD::BITCAST, dl, VT, 7079 DAG.getNode(ISD::XOR, dl, MVT::v2i64, 7080 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7081 Op.getOperand(0)), 7082 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask))); 7083 } else { 7084 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask); 7085 } 7086} 7087 7088SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 7089 LLVMContext *Context = DAG.getContext(); 7090 SDValue Op0 = Op.getOperand(0); 7091 SDValue Op1 = Op.getOperand(1); 7092 DebugLoc dl = Op.getDebugLoc(); 7093 EVT VT = Op.getValueType(); 7094 EVT SrcVT = Op1.getValueType(); 7095 7096 // If second operand is smaller, extend it first. 7097 if (SrcVT.bitsLT(VT)) { 7098 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1); 7099 SrcVT = VT; 7100 } 7101 // And if it is bigger, shrink it first. 7102 if (SrcVT.bitsGT(VT)) { 7103 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1)); 7104 SrcVT = VT; 7105 } 7106 7107 // At this point the operands and the result should have the same 7108 // type, and that won't be f80 since that is not custom lowered. 7109 7110 // First get the sign bit of second operand. 7111 std::vector<Constant*> CV; 7112 if (SrcVT == MVT::f64) { 7113 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)))); 7114 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 7115 } else { 7116 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)))); 7117 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7118 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7119 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7120 } 7121 Constant *C = ConstantVector::get(CV); 7122 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7123 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx, 7124 MachinePointerInfo::getConstantPool(), 7125 false, false, 16); 7126 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1); 7127 7128 // Shift sign bit right or left if the two operands have different types. 7129 if (SrcVT.bitsGT(VT)) { 7130 // Op0 is MVT::f32, Op1 is MVT::f64. 7131 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit); 7132 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit, 7133 DAG.getConstant(32, MVT::i32)); 7134 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit); 7135 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit, 7136 DAG.getIntPtrConstant(0)); 7137 } 7138 7139 // Clear first operand sign bit. 7140 CV.clear(); 7141 if (VT == MVT::f64) { 7142 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))))); 7143 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 7144 } else { 7145 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))))); 7146 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7147 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7148 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7149 } 7150 C = ConstantVector::get(CV); 7151 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7152 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 7153 MachinePointerInfo::getConstantPool(), 7154 false, false, 16); 7155 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2); 7156 7157 // Or the value with the sign bit. 7158 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit); 7159} 7160 7161/// Emit nodes that will be selected as "test Op0,Op0", or something 7162/// equivalent. 7163SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, 7164 SelectionDAG &DAG) const { 7165 DebugLoc dl = Op.getDebugLoc(); 7166 7167 // CF and OF aren't always set the way we want. Determine which 7168 // of these we need. 7169 bool NeedCF = false; 7170 bool NeedOF = false; 7171 switch (X86CC) { 7172 default: break; 7173 case X86::COND_A: case X86::COND_AE: 7174 case X86::COND_B: case X86::COND_BE: 7175 NeedCF = true; 7176 break; 7177 case X86::COND_G: case X86::COND_GE: 7178 case X86::COND_L: case X86::COND_LE: 7179 case X86::COND_O: case X86::COND_NO: 7180 NeedOF = true; 7181 break; 7182 } 7183 7184 // See if we can use the EFLAGS value from the operand instead of 7185 // doing a separate TEST. TEST always sets OF and CF to 0, so unless 7186 // we prove that the arithmetic won't overflow, we can't use OF or CF. 7187 if (Op.getResNo() != 0 || NeedOF || NeedCF) 7188 // Emit a CMP with 0, which is the TEST pattern. 7189 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 7190 DAG.getConstant(0, Op.getValueType())); 7191 7192 unsigned Opcode = 0; 7193 unsigned NumOperands = 0; 7194 switch (Op.getNode()->getOpcode()) { 7195 case ISD::ADD: 7196 // Due to an isel shortcoming, be conservative if this add is likely to be 7197 // selected as part of a load-modify-store instruction. When the root node 7198 // in a match is a store, isel doesn't know how to remap non-chain non-flag 7199 // uses of other nodes in the match, such as the ADD in this case. This 7200 // leads to the ADD being left around and reselected, with the result being 7201 // two adds in the output. Alas, even if none our users are stores, that 7202 // doesn't prove we're O.K. Ergo, if we have any parents that aren't 7203 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require 7204 // climbing the DAG back to the root, and it doesn't seem to be worth the 7205 // effort. 7206 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 7207 UE = Op.getNode()->use_end(); UI != UE; ++UI) 7208 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC) 7209 goto default_case; 7210 7211 if (ConstantSDNode *C = 7212 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) { 7213 // An add of one will be selected as an INC. 7214 if (C->getAPIntValue() == 1) { 7215 Opcode = X86ISD::INC; 7216 NumOperands = 1; 7217 break; 7218 } 7219 7220 // An add of negative one (subtract of one) will be selected as a DEC. 7221 if (C->getAPIntValue().isAllOnesValue()) { 7222 Opcode = X86ISD::DEC; 7223 NumOperands = 1; 7224 break; 7225 } 7226 } 7227 7228 // Otherwise use a regular EFLAGS-setting add. 7229 Opcode = X86ISD::ADD; 7230 NumOperands = 2; 7231 break; 7232 case ISD::AND: { 7233 // If the primary and result isn't used, don't bother using X86ISD::AND, 7234 // because a TEST instruction will be better. 7235 bool NonFlagUse = false; 7236 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 7237 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 7238 SDNode *User = *UI; 7239 unsigned UOpNo = UI.getOperandNo(); 7240 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) { 7241 // Look pass truncate. 7242 UOpNo = User->use_begin().getOperandNo(); 7243 User = *User->use_begin(); 7244 } 7245 7246 if (User->getOpcode() != ISD::BRCOND && 7247 User->getOpcode() != ISD::SETCC && 7248 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) { 7249 NonFlagUse = true; 7250 break; 7251 } 7252 } 7253 7254 if (!NonFlagUse) 7255 break; 7256 } 7257 // FALL THROUGH 7258 case ISD::SUB: 7259 case ISD::OR: 7260 case ISD::XOR: 7261 // Due to the ISEL shortcoming noted above, be conservative if this op is 7262 // likely to be selected as part of a load-modify-store instruction. 7263 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 7264 UE = Op.getNode()->use_end(); UI != UE; ++UI) 7265 if (UI->getOpcode() == ISD::STORE) 7266 goto default_case; 7267 7268 // Otherwise use a regular EFLAGS-setting instruction. 7269 switch (Op.getNode()->getOpcode()) { 7270 default: llvm_unreachable("unexpected operator!"); 7271 case ISD::SUB: Opcode = X86ISD::SUB; break; 7272 case ISD::OR: Opcode = X86ISD::OR; break; 7273 case ISD::XOR: Opcode = X86ISD::XOR; break; 7274 case ISD::AND: Opcode = X86ISD::AND; break; 7275 } 7276 7277 NumOperands = 2; 7278 break; 7279 case X86ISD::ADD: 7280 case X86ISD::SUB: 7281 case X86ISD::INC: 7282 case X86ISD::DEC: 7283 case X86ISD::OR: 7284 case X86ISD::XOR: 7285 case X86ISD::AND: 7286 return SDValue(Op.getNode(), 1); 7287 default: 7288 default_case: 7289 break; 7290 } 7291 7292 if (Opcode == 0) 7293 // Emit a CMP with 0, which is the TEST pattern. 7294 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 7295 DAG.getConstant(0, Op.getValueType())); 7296 7297 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 7298 SmallVector<SDValue, 4> Ops; 7299 for (unsigned i = 0; i != NumOperands; ++i) 7300 Ops.push_back(Op.getOperand(i)); 7301 7302 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands); 7303 DAG.ReplaceAllUsesWith(Op, New); 7304 return SDValue(New.getNode(), 1); 7305} 7306 7307/// Emit nodes that will be selected as "cmp Op0,Op1", or something 7308/// equivalent. 7309SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC, 7310 SelectionDAG &DAG) const { 7311 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) 7312 if (C->getAPIntValue() == 0) 7313 return EmitTest(Op0, X86CC, DAG); 7314 7315 DebugLoc dl = Op0.getDebugLoc(); 7316 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1); 7317} 7318 7319/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node 7320/// if it's possible. 7321SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC, 7322 DebugLoc dl, SelectionDAG &DAG) const { 7323 SDValue Op0 = And.getOperand(0); 7324 SDValue Op1 = And.getOperand(1); 7325 if (Op0.getOpcode() == ISD::TRUNCATE) 7326 Op0 = Op0.getOperand(0); 7327 if (Op1.getOpcode() == ISD::TRUNCATE) 7328 Op1 = Op1.getOperand(0); 7329 7330 SDValue LHS, RHS; 7331 if (Op1.getOpcode() == ISD::SHL) 7332 std::swap(Op0, Op1); 7333 if (Op0.getOpcode() == ISD::SHL) { 7334 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0))) 7335 if (And00C->getZExtValue() == 1) { 7336 // If we looked past a truncate, check that it's only truncating away 7337 // known zeros. 7338 unsigned BitWidth = Op0.getValueSizeInBits(); 7339 unsigned AndBitWidth = And.getValueSizeInBits(); 7340 if (BitWidth > AndBitWidth) { 7341 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones; 7342 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones); 7343 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth) 7344 return SDValue(); 7345 } 7346 LHS = Op1; 7347 RHS = Op0.getOperand(1); 7348 } 7349 } else if (Op1.getOpcode() == ISD::Constant) { 7350 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1); 7351 SDValue AndLHS = Op0; 7352 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) { 7353 LHS = AndLHS.getOperand(0); 7354 RHS = AndLHS.getOperand(1); 7355 } 7356 } 7357 7358 if (LHS.getNode()) { 7359 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT 7360 // instruction. Since the shift amount is in-range-or-undefined, we know 7361 // that doing a bittest on the i32 value is ok. We extend to i32 because 7362 // the encoding for the i16 version is larger than the i32 version. 7363 // Also promote i16 to i32 for performance / code size reason. 7364 if (LHS.getValueType() == MVT::i8 || 7365 LHS.getValueType() == MVT::i16) 7366 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 7367 7368 // If the operand types disagree, extend the shift amount to match. Since 7369 // BT ignores high bits (like shifts) we can use anyextend. 7370 if (LHS.getValueType() != RHS.getValueType()) 7371 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS); 7372 7373 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS); 7374 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B; 7375 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 7376 DAG.getConstant(Cond, MVT::i8), BT); 7377 } 7378 7379 return SDValue(); 7380} 7381 7382SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 7383 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer"); 7384 SDValue Op0 = Op.getOperand(0); 7385 SDValue Op1 = Op.getOperand(1); 7386 DebugLoc dl = Op.getDebugLoc(); 7387 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7388 7389 // Optimize to BT if possible. 7390 // Lower (X & (1 << N)) == 0 to BT(X, N). 7391 // Lower ((X >>u N) & 1) != 0 to BT(X, N). 7392 // Lower ((X >>s N) & 1) != 0 to BT(X, N). 7393 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && 7394 Op1.getOpcode() == ISD::Constant && 7395 cast<ConstantSDNode>(Op1)->isNullValue() && 7396 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 7397 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG); 7398 if (NewSetCC.getNode()) 7399 return NewSetCC; 7400 } 7401 7402 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of 7403 // these. 7404 if (Op1.getOpcode() == ISD::Constant && 7405 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 || 7406 cast<ConstantSDNode>(Op1)->isNullValue()) && 7407 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 7408 7409 // If the input is a setcc, then reuse the input setcc or use a new one with 7410 // the inverted condition. 7411 if (Op0.getOpcode() == X86ISD::SETCC) { 7412 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0); 7413 bool Invert = (CC == ISD::SETNE) ^ 7414 cast<ConstantSDNode>(Op1)->isNullValue(); 7415 if (!Invert) return Op0; 7416 7417 CCode = X86::GetOppositeBranchCondition(CCode); 7418 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 7419 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1)); 7420 } 7421 } 7422 7423 bool isFP = Op1.getValueType().isFloatingPoint(); 7424 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 7425 if (X86CC == X86::COND_INVALID) 7426 return SDValue(); 7427 7428 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG); 7429 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 7430 DAG.getConstant(X86CC, MVT::i8), EFLAGS); 7431} 7432 7433SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const { 7434 SDValue Cond; 7435 SDValue Op0 = Op.getOperand(0); 7436 SDValue Op1 = Op.getOperand(1); 7437 SDValue CC = Op.getOperand(2); 7438 EVT VT = Op.getValueType(); 7439 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 7440 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint(); 7441 DebugLoc dl = Op.getDebugLoc(); 7442 7443 if (isFP) { 7444 unsigned SSECC = 8; 7445 EVT VT0 = Op0.getValueType(); 7446 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64); 7447 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD; 7448 bool Swap = false; 7449 7450 switch (SetCCOpcode) { 7451 default: break; 7452 case ISD::SETOEQ: 7453 case ISD::SETEQ: SSECC = 0; break; 7454 case ISD::SETOGT: 7455 case ISD::SETGT: Swap = true; // Fallthrough 7456 case ISD::SETLT: 7457 case ISD::SETOLT: SSECC = 1; break; 7458 case ISD::SETOGE: 7459 case ISD::SETGE: Swap = true; // Fallthrough 7460 case ISD::SETLE: 7461 case ISD::SETOLE: SSECC = 2; break; 7462 case ISD::SETUO: SSECC = 3; break; 7463 case ISD::SETUNE: 7464 case ISD::SETNE: SSECC = 4; break; 7465 case ISD::SETULE: Swap = true; 7466 case ISD::SETUGE: SSECC = 5; break; 7467 case ISD::SETULT: Swap = true; 7468 case ISD::SETUGT: SSECC = 6; break; 7469 case ISD::SETO: SSECC = 7; break; 7470 } 7471 if (Swap) 7472 std::swap(Op0, Op1); 7473 7474 // In the two special cases we can't handle, emit two comparisons. 7475 if (SSECC == 8) { 7476 if (SetCCOpcode == ISD::SETUEQ) { 7477 SDValue UNORD, EQ; 7478 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8)); 7479 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8)); 7480 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ); 7481 } 7482 else if (SetCCOpcode == ISD::SETONE) { 7483 SDValue ORD, NEQ; 7484 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8)); 7485 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8)); 7486 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ); 7487 } 7488 llvm_unreachable("Illegal FP comparison"); 7489 } 7490 // Handle all other FP comparisons here. 7491 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8)); 7492 } 7493 7494 // We are handling one of the integer comparisons here. Since SSE only has 7495 // GT and EQ comparisons for integer, swapping operands and multiple 7496 // operations may be required for some comparisons. 7497 unsigned Opc = 0, EQOpc = 0, GTOpc = 0; 7498 bool Swap = false, Invert = false, FlipSigns = false; 7499 7500 switch (VT.getSimpleVT().SimpleTy) { 7501 default: break; 7502 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break; 7503 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break; 7504 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break; 7505 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break; 7506 } 7507 7508 switch (SetCCOpcode) { 7509 default: break; 7510 case ISD::SETNE: Invert = true; 7511 case ISD::SETEQ: Opc = EQOpc; break; 7512 case ISD::SETLT: Swap = true; 7513 case ISD::SETGT: Opc = GTOpc; break; 7514 case ISD::SETGE: Swap = true; 7515 case ISD::SETLE: Opc = GTOpc; Invert = true; break; 7516 case ISD::SETULT: Swap = true; 7517 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break; 7518 case ISD::SETUGE: Swap = true; 7519 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break; 7520 } 7521 if (Swap) 7522 std::swap(Op0, Op1); 7523 7524 // Since SSE has no unsigned integer comparisons, we need to flip the sign 7525 // bits of the inputs before performing those operations. 7526 if (FlipSigns) { 7527 EVT EltVT = VT.getVectorElementType(); 7528 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), 7529 EltVT); 7530 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit); 7531 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0], 7532 SignBits.size()); 7533 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec); 7534 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec); 7535 } 7536 7537 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 7538 7539 // If the logical-not of the result is required, perform that now. 7540 if (Invert) 7541 Result = DAG.getNOT(dl, Result, VT); 7542 7543 return Result; 7544} 7545 7546// isX86LogicalCmp - Return true if opcode is a X86 logical comparison. 7547static bool isX86LogicalCmp(SDValue Op) { 7548 unsigned Opc = Op.getNode()->getOpcode(); 7549 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) 7550 return true; 7551 if (Op.getResNo() == 1 && 7552 (Opc == X86ISD::ADD || 7553 Opc == X86ISD::SUB || 7554 Opc == X86ISD::ADC || 7555 Opc == X86ISD::SBB || 7556 Opc == X86ISD::SMUL || 7557 Opc == X86ISD::UMUL || 7558 Opc == X86ISD::INC || 7559 Opc == X86ISD::DEC || 7560 Opc == X86ISD::OR || 7561 Opc == X86ISD::XOR || 7562 Opc == X86ISD::AND)) 7563 return true; 7564 7565 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL) 7566 return true; 7567 7568 return false; 7569} 7570 7571static bool isZero(SDValue V) { 7572 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 7573 return C && C->isNullValue(); 7574} 7575 7576static bool isAllOnes(SDValue V) { 7577 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 7578 return C && C->isAllOnesValue(); 7579} 7580 7581SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7582 bool addTest = true; 7583 SDValue Cond = Op.getOperand(0); 7584 SDValue Op1 = Op.getOperand(1); 7585 SDValue Op2 = Op.getOperand(2); 7586 DebugLoc DL = Op.getDebugLoc(); 7587 SDValue CC; 7588 7589 if (Cond.getOpcode() == ISD::SETCC) { 7590 SDValue NewCond = LowerSETCC(Cond, DAG); 7591 if (NewCond.getNode()) 7592 Cond = NewCond; 7593 } 7594 7595 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y 7596 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y 7597 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y 7598 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y 7599 if (Cond.getOpcode() == X86ISD::SETCC && 7600 Cond.getOperand(1).getOpcode() == X86ISD::CMP && 7601 isZero(Cond.getOperand(1).getOperand(1))) { 7602 SDValue Cmp = Cond.getOperand(1); 7603 7604 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue(); 7605 7606 if ((isAllOnes(Op1) || isAllOnes(Op2)) && 7607 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) { 7608 SDValue Y = isAllOnes(Op2) ? Op1 : Op2; 7609 7610 SDValue CmpOp0 = Cmp.getOperand(0); 7611 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, 7612 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType())); 7613 7614 SDValue Res = // Res = 0 or -1. 7615 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 7616 DAG.getConstant(X86::COND_B, MVT::i8), Cmp); 7617 7618 if (isAllOnes(Op1) != (CondCode == X86::COND_E)) 7619 Res = DAG.getNOT(DL, Res, Res.getValueType()); 7620 7621 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2); 7622 if (N2C == 0 || !N2C->isNullValue()) 7623 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y); 7624 return Res; 7625 } 7626 } 7627 7628 // Look past (and (setcc_carry (cmp ...)), 1). 7629 if (Cond.getOpcode() == ISD::AND && 7630 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 7631 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 7632 if (C && C->getAPIntValue() == 1) 7633 Cond = Cond.getOperand(0); 7634 } 7635 7636 // If condition flag is set by a X86ISD::CMP, then use it as the condition 7637 // setting operand in place of the X86ISD::SETCC. 7638 if (Cond.getOpcode() == X86ISD::SETCC || 7639 Cond.getOpcode() == X86ISD::SETCC_CARRY) { 7640 CC = Cond.getOperand(0); 7641 7642 SDValue Cmp = Cond.getOperand(1); 7643 unsigned Opc = Cmp.getOpcode(); 7644 EVT VT = Op.getValueType(); 7645 7646 bool IllegalFPCMov = false; 7647 if (VT.isFloatingPoint() && !VT.isVector() && 7648 !isScalarFPTypeInSSEReg(VT)) // FPStack? 7649 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue()); 7650 7651 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || 7652 Opc == X86ISD::BT) { // FIXME 7653 Cond = Cmp; 7654 addTest = false; 7655 } 7656 } 7657 7658 if (addTest) { 7659 // Look pass the truncate. 7660 if (Cond.getOpcode() == ISD::TRUNCATE) 7661 Cond = Cond.getOperand(0); 7662 7663 // We know the result of AND is compared against zero. Try to match 7664 // it to BT. 7665 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 7666 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG); 7667 if (NewSetCC.getNode()) { 7668 CC = NewSetCC.getOperand(0); 7669 Cond = NewSetCC.getOperand(1); 7670 addTest = false; 7671 } 7672 } 7673 } 7674 7675 if (addTest) { 7676 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7677 Cond = EmitTest(Cond, X86::COND_NE, DAG); 7678 } 7679 7680 // a < b ? -1 : 0 -> RES = ~setcc_carry 7681 // a < b ? 0 : -1 -> RES = setcc_carry 7682 // a >= b ? -1 : 0 -> RES = setcc_carry 7683 // a >= b ? 0 : -1 -> RES = ~setcc_carry 7684 if (Cond.getOpcode() == X86ISD::CMP) { 7685 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue(); 7686 7687 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) && 7688 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) { 7689 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 7690 DAG.getConstant(X86::COND_B, MVT::i8), Cond); 7691 if (isAllOnes(Op1) != (CondCode == X86::COND_B)) 7692 return DAG.getNOT(DL, Res, Res.getValueType()); 7693 return Res; 7694 } 7695 } 7696 7697 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if 7698 // condition is true. 7699 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 7700 SDValue Ops[] = { Op2, Op1, CC, Cond }; 7701 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops)); 7702} 7703 7704// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or 7705// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart 7706// from the AND / OR. 7707static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) { 7708 Opc = Op.getOpcode(); 7709 if (Opc != ISD::OR && Opc != ISD::AND) 7710 return false; 7711 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC && 7712 Op.getOperand(0).hasOneUse() && 7713 Op.getOperand(1).getOpcode() == X86ISD::SETCC && 7714 Op.getOperand(1).hasOneUse()); 7715} 7716 7717// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and 7718// 1 and that the SETCC node has a single use. 7719static bool isXor1OfSetCC(SDValue Op) { 7720 if (Op.getOpcode() != ISD::XOR) 7721 return false; 7722 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7723 if (N1C && N1C->getAPIntValue() == 1) { 7724 return Op.getOperand(0).getOpcode() == X86ISD::SETCC && 7725 Op.getOperand(0).hasOneUse(); 7726 } 7727 return false; 7728} 7729 7730SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 7731 bool addTest = true; 7732 SDValue Chain = Op.getOperand(0); 7733 SDValue Cond = Op.getOperand(1); 7734 SDValue Dest = Op.getOperand(2); 7735 DebugLoc dl = Op.getDebugLoc(); 7736 SDValue CC; 7737 7738 if (Cond.getOpcode() == ISD::SETCC) { 7739 SDValue NewCond = LowerSETCC(Cond, DAG); 7740 if (NewCond.getNode()) 7741 Cond = NewCond; 7742 } 7743#if 0 7744 // FIXME: LowerXALUO doesn't handle these!! 7745 else if (Cond.getOpcode() == X86ISD::ADD || 7746 Cond.getOpcode() == X86ISD::SUB || 7747 Cond.getOpcode() == X86ISD::SMUL || 7748 Cond.getOpcode() == X86ISD::UMUL) 7749 Cond = LowerXALUO(Cond, DAG); 7750#endif 7751 7752 // Look pass (and (setcc_carry (cmp ...)), 1). 7753 if (Cond.getOpcode() == ISD::AND && 7754 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 7755 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 7756 if (C && C->getAPIntValue() == 1) 7757 Cond = Cond.getOperand(0); 7758 } 7759 7760 // If condition flag is set by a X86ISD::CMP, then use it as the condition 7761 // setting operand in place of the X86ISD::SETCC. 7762 if (Cond.getOpcode() == X86ISD::SETCC || 7763 Cond.getOpcode() == X86ISD::SETCC_CARRY) { 7764 CC = Cond.getOperand(0); 7765 7766 SDValue Cmp = Cond.getOperand(1); 7767 unsigned Opc = Cmp.getOpcode(); 7768 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp?? 7769 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) { 7770 Cond = Cmp; 7771 addTest = false; 7772 } else { 7773 switch (cast<ConstantSDNode>(CC)->getZExtValue()) { 7774 default: break; 7775 case X86::COND_O: 7776 case X86::COND_B: 7777 // These can only come from an arithmetic instruction with overflow, 7778 // e.g. SADDO, UADDO. 7779 Cond = Cond.getNode()->getOperand(1); 7780 addTest = false; 7781 break; 7782 } 7783 } 7784 } else { 7785 unsigned CondOpc; 7786 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) { 7787 SDValue Cmp = Cond.getOperand(0).getOperand(1); 7788 if (CondOpc == ISD::OR) { 7789 // Also, recognize the pattern generated by an FCMP_UNE. We can emit 7790 // two branches instead of an explicit OR instruction with a 7791 // separate test. 7792 if (Cmp == Cond.getOperand(1).getOperand(1) && 7793 isX86LogicalCmp(Cmp)) { 7794 CC = Cond.getOperand(0).getOperand(0); 7795 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 7796 Chain, Dest, CC, Cmp); 7797 CC = Cond.getOperand(1).getOperand(0); 7798 Cond = Cmp; 7799 addTest = false; 7800 } 7801 } else { // ISD::AND 7802 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit 7803 // two branches instead of an explicit AND instruction with a 7804 // separate test. However, we only do this if this block doesn't 7805 // have a fall-through edge, because this requires an explicit 7806 // jmp when the condition is false. 7807 if (Cmp == Cond.getOperand(1).getOperand(1) && 7808 isX86LogicalCmp(Cmp) && 7809 Op.getNode()->hasOneUse()) { 7810 X86::CondCode CCode = 7811 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 7812 CCode = X86::GetOppositeBranchCondition(CCode); 7813 CC = DAG.getConstant(CCode, MVT::i8); 7814 SDNode *User = *Op.getNode()->use_begin(); 7815 // Look for an unconditional branch following this conditional branch. 7816 // We need this because we need to reverse the successors in order 7817 // to implement FCMP_OEQ. 7818 if (User->getOpcode() == ISD::BR) { 7819 SDValue FalseBB = User->getOperand(1); 7820 SDNode *NewBR = 7821 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 7822 assert(NewBR == User); 7823 (void)NewBR; 7824 Dest = FalseBB; 7825 7826 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 7827 Chain, Dest, CC, Cmp); 7828 X86::CondCode CCode = 7829 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0); 7830 CCode = X86::GetOppositeBranchCondition(CCode); 7831 CC = DAG.getConstant(CCode, MVT::i8); 7832 Cond = Cmp; 7833 addTest = false; 7834 } 7835 } 7836 } 7837 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) { 7838 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition. 7839 // It should be transformed during dag combiner except when the condition 7840 // is set by a arithmetics with overflow node. 7841 X86::CondCode CCode = 7842 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 7843 CCode = X86::GetOppositeBranchCondition(CCode); 7844 CC = DAG.getConstant(CCode, MVT::i8); 7845 Cond = Cond.getOperand(0).getOperand(1); 7846 addTest = false; 7847 } 7848 } 7849 7850 if (addTest) { 7851 // Look pass the truncate. 7852 if (Cond.getOpcode() == ISD::TRUNCATE) 7853 Cond = Cond.getOperand(0); 7854 7855 // We know the result of AND is compared against zero. Try to match 7856 // it to BT. 7857 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 7858 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG); 7859 if (NewSetCC.getNode()) { 7860 CC = NewSetCC.getOperand(0); 7861 Cond = NewSetCC.getOperand(1); 7862 addTest = false; 7863 } 7864 } 7865 } 7866 7867 if (addTest) { 7868 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7869 Cond = EmitTest(Cond, X86::COND_NE, DAG); 7870 } 7871 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 7872 Chain, Dest, CC, Cond); 7873} 7874 7875 7876// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets. 7877// Calls to _alloca is needed to probe the stack when allocating more than 4k 7878// bytes in one go. Touching the stack at 4K increments is necessary to ensure 7879// that the guard pages used by the OS virtual memory manager are allocated in 7880// correct sequence. 7881SDValue 7882X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7883 SelectionDAG &DAG) const { 7884 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) && 7885 "This should be used only on Windows targets"); 7886 DebugLoc dl = Op.getDebugLoc(); 7887 7888 // Get the inputs. 7889 SDValue Chain = Op.getOperand(0); 7890 SDValue Size = Op.getOperand(1); 7891 // FIXME: Ensure alignment here 7892 7893 SDValue Flag; 7894 7895 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32; 7896 7897 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag); 7898 Flag = Chain.getValue(1); 7899 7900 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7901 7902 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag); 7903 Flag = Chain.getValue(1); 7904 7905 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1); 7906 7907 SDValue Ops1[2] = { Chain.getValue(0), Chain }; 7908 return DAG.getMergeValues(Ops1, 2, dl); 7909} 7910 7911SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 7912 MachineFunction &MF = DAG.getMachineFunction(); 7913 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 7914 7915 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7916 DebugLoc DL = Op.getDebugLoc(); 7917 7918 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) { 7919 // vastart just stores the address of the VarArgsFrameIndex slot into the 7920 // memory location argument. 7921 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 7922 getPointerTy()); 7923 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 7924 MachinePointerInfo(SV), false, false, 0); 7925 } 7926 7927 // __va_list_tag: 7928 // gp_offset (0 - 6 * 8) 7929 // fp_offset (48 - 48 + 8 * 16) 7930 // overflow_arg_area (point to parameters coming in memory). 7931 // reg_save_area 7932 SmallVector<SDValue, 8> MemOps; 7933 SDValue FIN = Op.getOperand(1); 7934 // Store gp_offset 7935 SDValue Store = DAG.getStore(Op.getOperand(0), DL, 7936 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), 7937 MVT::i32), 7938 FIN, MachinePointerInfo(SV), false, false, 0); 7939 MemOps.push_back(Store); 7940 7941 // Store fp_offset 7942 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7943 FIN, DAG.getIntPtrConstant(4)); 7944 Store = DAG.getStore(Op.getOperand(0), DL, 7945 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), 7946 MVT::i32), 7947 FIN, MachinePointerInfo(SV, 4), false, false, 0); 7948 MemOps.push_back(Store); 7949 7950 // Store ptr to overflow_arg_area 7951 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7952 FIN, DAG.getIntPtrConstant(4)); 7953 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 7954 getPointerTy()); 7955 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, 7956 MachinePointerInfo(SV, 8), 7957 false, false, 0); 7958 MemOps.push_back(Store); 7959 7960 // Store ptr to reg_save_area. 7961 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7962 FIN, DAG.getIntPtrConstant(8)); 7963 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 7964 getPointerTy()); 7965 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, 7966 MachinePointerInfo(SV, 16), false, false, 0); 7967 MemOps.push_back(Store); 7968 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 7969 &MemOps[0], MemOps.size()); 7970} 7971 7972SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 7973 assert(Subtarget->is64Bit() && 7974 "LowerVAARG only handles 64-bit va_arg!"); 7975 assert((Subtarget->isTargetLinux() || 7976 Subtarget->isTargetDarwin()) && 7977 "Unhandled target in LowerVAARG"); 7978 assert(Op.getNode()->getNumOperands() == 4); 7979 SDValue Chain = Op.getOperand(0); 7980 SDValue SrcPtr = Op.getOperand(1); 7981 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7982 unsigned Align = Op.getConstantOperandVal(3); 7983 DebugLoc dl = Op.getDebugLoc(); 7984 7985 EVT ArgVT = Op.getNode()->getValueType(0); 7986 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7987 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy); 7988 uint8_t ArgMode; 7989 7990 // Decide which area this value should be read from. 7991 // TODO: Implement the AMD64 ABI in its entirety. This simple 7992 // selection mechanism works only for the basic types. 7993 if (ArgVT == MVT::f80) { 7994 llvm_unreachable("va_arg for f80 not yet implemented"); 7995 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) { 7996 ArgMode = 2; // Argument passed in XMM register. Use fp_offset. 7997 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) { 7998 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset. 7999 } else { 8000 llvm_unreachable("Unhandled argument type in LowerVAARG"); 8001 } 8002 8003 if (ArgMode == 2) { 8004 // Sanity Check: Make sure using fp_offset makes sense. 8005 assert(!UseSoftFloat && 8006 !(DAG.getMachineFunction() 8007 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) && 8008 Subtarget->hasXMM()); 8009 } 8010 8011 // Insert VAARG_64 node into the DAG 8012 // VAARG_64 returns two values: Variable Argument Address, Chain 8013 SmallVector<SDValue, 11> InstOps; 8014 InstOps.push_back(Chain); 8015 InstOps.push_back(SrcPtr); 8016 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32)); 8017 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8)); 8018 InstOps.push_back(DAG.getConstant(Align, MVT::i32)); 8019 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other); 8020 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl, 8021 VTs, &InstOps[0], InstOps.size(), 8022 MVT::i64, 8023 MachinePointerInfo(SV), 8024 /*Align=*/0, 8025 /*Volatile=*/false, 8026 /*ReadMem=*/true, 8027 /*WriteMem=*/true); 8028 Chain = VAARG.getValue(1); 8029 8030 // Load the next argument and return it 8031 return DAG.getLoad(ArgVT, dl, 8032 Chain, 8033 VAARG, 8034 MachinePointerInfo(), 8035 false, false, 0); 8036} 8037 8038SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 8039 // X86-64 va_list is a struct { i32, i32, i8*, i8* }. 8040 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!"); 8041 SDValue Chain = Op.getOperand(0); 8042 SDValue DstPtr = Op.getOperand(1); 8043 SDValue SrcPtr = Op.getOperand(2); 8044 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 8045 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 8046 DebugLoc DL = Op.getDebugLoc(); 8047 8048 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, 8049 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false, 8050 false, 8051 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 8052} 8053 8054SDValue 8055X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const { 8056 DebugLoc dl = Op.getDebugLoc(); 8057 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8058 switch (IntNo) { 8059 default: return SDValue(); // Don't custom lower most intrinsics. 8060 // Comparison intrinsics. 8061 case Intrinsic::x86_sse_comieq_ss: 8062 case Intrinsic::x86_sse_comilt_ss: 8063 case Intrinsic::x86_sse_comile_ss: 8064 case Intrinsic::x86_sse_comigt_ss: 8065 case Intrinsic::x86_sse_comige_ss: 8066 case Intrinsic::x86_sse_comineq_ss: 8067 case Intrinsic::x86_sse_ucomieq_ss: 8068 case Intrinsic::x86_sse_ucomilt_ss: 8069 case Intrinsic::x86_sse_ucomile_ss: 8070 case Intrinsic::x86_sse_ucomigt_ss: 8071 case Intrinsic::x86_sse_ucomige_ss: 8072 case Intrinsic::x86_sse_ucomineq_ss: 8073 case Intrinsic::x86_sse2_comieq_sd: 8074 case Intrinsic::x86_sse2_comilt_sd: 8075 case Intrinsic::x86_sse2_comile_sd: 8076 case Intrinsic::x86_sse2_comigt_sd: 8077 case Intrinsic::x86_sse2_comige_sd: 8078 case Intrinsic::x86_sse2_comineq_sd: 8079 case Intrinsic::x86_sse2_ucomieq_sd: 8080 case Intrinsic::x86_sse2_ucomilt_sd: 8081 case Intrinsic::x86_sse2_ucomile_sd: 8082 case Intrinsic::x86_sse2_ucomigt_sd: 8083 case Intrinsic::x86_sse2_ucomige_sd: 8084 case Intrinsic::x86_sse2_ucomineq_sd: { 8085 unsigned Opc = 0; 8086 ISD::CondCode CC = ISD::SETCC_INVALID; 8087 switch (IntNo) { 8088 default: break; 8089 case Intrinsic::x86_sse_comieq_ss: 8090 case Intrinsic::x86_sse2_comieq_sd: 8091 Opc = X86ISD::COMI; 8092 CC = ISD::SETEQ; 8093 break; 8094 case Intrinsic::x86_sse_comilt_ss: 8095 case Intrinsic::x86_sse2_comilt_sd: 8096 Opc = X86ISD::COMI; 8097 CC = ISD::SETLT; 8098 break; 8099 case Intrinsic::x86_sse_comile_ss: 8100 case Intrinsic::x86_sse2_comile_sd: 8101 Opc = X86ISD::COMI; 8102 CC = ISD::SETLE; 8103 break; 8104 case Intrinsic::x86_sse_comigt_ss: 8105 case Intrinsic::x86_sse2_comigt_sd: 8106 Opc = X86ISD::COMI; 8107 CC = ISD::SETGT; 8108 break; 8109 case Intrinsic::x86_sse_comige_ss: 8110 case Intrinsic::x86_sse2_comige_sd: 8111 Opc = X86ISD::COMI; 8112 CC = ISD::SETGE; 8113 break; 8114 case Intrinsic::x86_sse_comineq_ss: 8115 case Intrinsic::x86_sse2_comineq_sd: 8116 Opc = X86ISD::COMI; 8117 CC = ISD::SETNE; 8118 break; 8119 case Intrinsic::x86_sse_ucomieq_ss: 8120 case Intrinsic::x86_sse2_ucomieq_sd: 8121 Opc = X86ISD::UCOMI; 8122 CC = ISD::SETEQ; 8123 break; 8124 case Intrinsic::x86_sse_ucomilt_ss: 8125 case Intrinsic::x86_sse2_ucomilt_sd: 8126 Opc = X86ISD::UCOMI; 8127 CC = ISD::SETLT; 8128 break; 8129 case Intrinsic::x86_sse_ucomile_ss: 8130 case Intrinsic::x86_sse2_ucomile_sd: 8131 Opc = X86ISD::UCOMI; 8132 CC = ISD::SETLE; 8133 break; 8134 case Intrinsic::x86_sse_ucomigt_ss: 8135 case Intrinsic::x86_sse2_ucomigt_sd: 8136 Opc = X86ISD::UCOMI; 8137 CC = ISD::SETGT; 8138 break; 8139 case Intrinsic::x86_sse_ucomige_ss: 8140 case Intrinsic::x86_sse2_ucomige_sd: 8141 Opc = X86ISD::UCOMI; 8142 CC = ISD::SETGE; 8143 break; 8144 case Intrinsic::x86_sse_ucomineq_ss: 8145 case Intrinsic::x86_sse2_ucomineq_sd: 8146 Opc = X86ISD::UCOMI; 8147 CC = ISD::SETNE; 8148 break; 8149 } 8150 8151 SDValue LHS = Op.getOperand(1); 8152 SDValue RHS = Op.getOperand(2); 8153 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG); 8154 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!"); 8155 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS); 8156 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8157 DAG.getConstant(X86CC, MVT::i8), Cond); 8158 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 8159 } 8160 // ptest and testp intrinsics. The intrinsic these come from are designed to 8161 // return an integer value, not just an instruction so lower it to the ptest 8162 // or testp pattern and a setcc for the result. 8163 case Intrinsic::x86_sse41_ptestz: 8164 case Intrinsic::x86_sse41_ptestc: 8165 case Intrinsic::x86_sse41_ptestnzc: 8166 case Intrinsic::x86_avx_ptestz_256: 8167 case Intrinsic::x86_avx_ptestc_256: 8168 case Intrinsic::x86_avx_ptestnzc_256: 8169 case Intrinsic::x86_avx_vtestz_ps: 8170 case Intrinsic::x86_avx_vtestc_ps: 8171 case Intrinsic::x86_avx_vtestnzc_ps: 8172 case Intrinsic::x86_avx_vtestz_pd: 8173 case Intrinsic::x86_avx_vtestc_pd: 8174 case Intrinsic::x86_avx_vtestnzc_pd: 8175 case Intrinsic::x86_avx_vtestz_ps_256: 8176 case Intrinsic::x86_avx_vtestc_ps_256: 8177 case Intrinsic::x86_avx_vtestnzc_ps_256: 8178 case Intrinsic::x86_avx_vtestz_pd_256: 8179 case Intrinsic::x86_avx_vtestc_pd_256: 8180 case Intrinsic::x86_avx_vtestnzc_pd_256: { 8181 bool IsTestPacked = false; 8182 unsigned X86CC = 0; 8183 switch (IntNo) { 8184 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering."); 8185 case Intrinsic::x86_avx_vtestz_ps: 8186 case Intrinsic::x86_avx_vtestz_pd: 8187 case Intrinsic::x86_avx_vtestz_ps_256: 8188 case Intrinsic::x86_avx_vtestz_pd_256: 8189 IsTestPacked = true; // Fallthrough 8190 case Intrinsic::x86_sse41_ptestz: 8191 case Intrinsic::x86_avx_ptestz_256: 8192 // ZF = 1 8193 X86CC = X86::COND_E; 8194 break; 8195 case Intrinsic::x86_avx_vtestc_ps: 8196 case Intrinsic::x86_avx_vtestc_pd: 8197 case Intrinsic::x86_avx_vtestc_ps_256: 8198 case Intrinsic::x86_avx_vtestc_pd_256: 8199 IsTestPacked = true; // Fallthrough 8200 case Intrinsic::x86_sse41_ptestc: 8201 case Intrinsic::x86_avx_ptestc_256: 8202 // CF = 1 8203 X86CC = X86::COND_B; 8204 break; 8205 case Intrinsic::x86_avx_vtestnzc_ps: 8206 case Intrinsic::x86_avx_vtestnzc_pd: 8207 case Intrinsic::x86_avx_vtestnzc_ps_256: 8208 case Intrinsic::x86_avx_vtestnzc_pd_256: 8209 IsTestPacked = true; // Fallthrough 8210 case Intrinsic::x86_sse41_ptestnzc: 8211 case Intrinsic::x86_avx_ptestnzc_256: 8212 // ZF and CF = 0 8213 X86CC = X86::COND_A; 8214 break; 8215 } 8216 8217 SDValue LHS = Op.getOperand(1); 8218 SDValue RHS = Op.getOperand(2); 8219 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST; 8220 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS); 8221 SDValue CC = DAG.getConstant(X86CC, MVT::i8); 8222 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test); 8223 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 8224 } 8225 8226 // Fix vector shift instructions where the last operand is a non-immediate 8227 // i32 value. 8228 case Intrinsic::x86_sse2_pslli_w: 8229 case Intrinsic::x86_sse2_pslli_d: 8230 case Intrinsic::x86_sse2_pslli_q: 8231 case Intrinsic::x86_sse2_psrli_w: 8232 case Intrinsic::x86_sse2_psrli_d: 8233 case Intrinsic::x86_sse2_psrli_q: 8234 case Intrinsic::x86_sse2_psrai_w: 8235 case Intrinsic::x86_sse2_psrai_d: 8236 case Intrinsic::x86_mmx_pslli_w: 8237 case Intrinsic::x86_mmx_pslli_d: 8238 case Intrinsic::x86_mmx_pslli_q: 8239 case Intrinsic::x86_mmx_psrli_w: 8240 case Intrinsic::x86_mmx_psrli_d: 8241 case Intrinsic::x86_mmx_psrli_q: 8242 case Intrinsic::x86_mmx_psrai_w: 8243 case Intrinsic::x86_mmx_psrai_d: { 8244 SDValue ShAmt = Op.getOperand(2); 8245 if (isa<ConstantSDNode>(ShAmt)) 8246 return SDValue(); 8247 8248 unsigned NewIntNo = 0; 8249 EVT ShAmtVT = MVT::v4i32; 8250 switch (IntNo) { 8251 case Intrinsic::x86_sse2_pslli_w: 8252 NewIntNo = Intrinsic::x86_sse2_psll_w; 8253 break; 8254 case Intrinsic::x86_sse2_pslli_d: 8255 NewIntNo = Intrinsic::x86_sse2_psll_d; 8256 break; 8257 case Intrinsic::x86_sse2_pslli_q: 8258 NewIntNo = Intrinsic::x86_sse2_psll_q; 8259 break; 8260 case Intrinsic::x86_sse2_psrli_w: 8261 NewIntNo = Intrinsic::x86_sse2_psrl_w; 8262 break; 8263 case Intrinsic::x86_sse2_psrli_d: 8264 NewIntNo = Intrinsic::x86_sse2_psrl_d; 8265 break; 8266 case Intrinsic::x86_sse2_psrli_q: 8267 NewIntNo = Intrinsic::x86_sse2_psrl_q; 8268 break; 8269 case Intrinsic::x86_sse2_psrai_w: 8270 NewIntNo = Intrinsic::x86_sse2_psra_w; 8271 break; 8272 case Intrinsic::x86_sse2_psrai_d: 8273 NewIntNo = Intrinsic::x86_sse2_psra_d; 8274 break; 8275 default: { 8276 ShAmtVT = MVT::v2i32; 8277 switch (IntNo) { 8278 case Intrinsic::x86_mmx_pslli_w: 8279 NewIntNo = Intrinsic::x86_mmx_psll_w; 8280 break; 8281 case Intrinsic::x86_mmx_pslli_d: 8282 NewIntNo = Intrinsic::x86_mmx_psll_d; 8283 break; 8284 case Intrinsic::x86_mmx_pslli_q: 8285 NewIntNo = Intrinsic::x86_mmx_psll_q; 8286 break; 8287 case Intrinsic::x86_mmx_psrli_w: 8288 NewIntNo = Intrinsic::x86_mmx_psrl_w; 8289 break; 8290 case Intrinsic::x86_mmx_psrli_d: 8291 NewIntNo = Intrinsic::x86_mmx_psrl_d; 8292 break; 8293 case Intrinsic::x86_mmx_psrli_q: 8294 NewIntNo = Intrinsic::x86_mmx_psrl_q; 8295 break; 8296 case Intrinsic::x86_mmx_psrai_w: 8297 NewIntNo = Intrinsic::x86_mmx_psra_w; 8298 break; 8299 case Intrinsic::x86_mmx_psrai_d: 8300 NewIntNo = Intrinsic::x86_mmx_psra_d; 8301 break; 8302 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8303 } 8304 break; 8305 } 8306 } 8307 8308 // The vector shift intrinsics with scalars uses 32b shift amounts but 8309 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 8310 // to be zero. 8311 SDValue ShOps[4]; 8312 ShOps[0] = ShAmt; 8313 ShOps[1] = DAG.getConstant(0, MVT::i32); 8314 if (ShAmtVT == MVT::v4i32) { 8315 ShOps[2] = DAG.getUNDEF(MVT::i32); 8316 ShOps[3] = DAG.getUNDEF(MVT::i32); 8317 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4); 8318 } else { 8319 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2); 8320// FIXME this must be lowered to get rid of the invalid type. 8321 } 8322 8323 EVT VT = Op.getValueType(); 8324 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt); 8325 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8326 DAG.getConstant(NewIntNo, MVT::i32), 8327 Op.getOperand(1), ShAmt); 8328 } 8329 } 8330} 8331 8332SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, 8333 SelectionDAG &DAG) const { 8334 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 8335 MFI->setReturnAddressIsTaken(true); 8336 8337 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8338 DebugLoc dl = Op.getDebugLoc(); 8339 8340 if (Depth > 0) { 8341 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 8342 SDValue Offset = 8343 DAG.getConstant(TD->getPointerSize(), 8344 Subtarget->is64Bit() ? MVT::i64 : MVT::i32); 8345 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 8346 DAG.getNode(ISD::ADD, dl, getPointerTy(), 8347 FrameAddr, Offset), 8348 MachinePointerInfo(), false, false, 0); 8349 } 8350 8351 // Just load the return address. 8352 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); 8353 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 8354 RetAddrFI, MachinePointerInfo(), false, false, 0); 8355} 8356 8357SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 8358 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 8359 MFI->setFrameAddressIsTaken(true); 8360 8361 EVT VT = Op.getValueType(); 8362 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful 8363 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8364 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP; 8365 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 8366 while (Depth--) 8367 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 8368 MachinePointerInfo(), 8369 false, false, 0); 8370 return FrameAddr; 8371} 8372 8373SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op, 8374 SelectionDAG &DAG) const { 8375 return DAG.getIntPtrConstant(2*TD->getPointerSize()); 8376} 8377 8378SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const { 8379 MachineFunction &MF = DAG.getMachineFunction(); 8380 SDValue Chain = Op.getOperand(0); 8381 SDValue Offset = Op.getOperand(1); 8382 SDValue Handler = Op.getOperand(2); 8383 DebugLoc dl = Op.getDebugLoc(); 8384 8385 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, 8386 Subtarget->is64Bit() ? X86::RBP : X86::EBP, 8387 getPointerTy()); 8388 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX); 8389 8390 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame, 8391 DAG.getIntPtrConstant(TD->getPointerSize())); 8392 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset); 8393 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(), 8394 false, false, 0); 8395 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr); 8396 MF.getRegInfo().addLiveOut(StoreAddrReg); 8397 8398 return DAG.getNode(X86ISD::EH_RETURN, dl, 8399 MVT::Other, 8400 Chain, DAG.getRegister(StoreAddrReg, getPointerTy())); 8401} 8402 8403SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op, 8404 SelectionDAG &DAG) const { 8405 SDValue Root = Op.getOperand(0); 8406 SDValue Trmp = Op.getOperand(1); // trampoline 8407 SDValue FPtr = Op.getOperand(2); // nested function 8408 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 8409 DebugLoc dl = Op.getDebugLoc(); 8410 8411 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 8412 8413 if (Subtarget->is64Bit()) { 8414 SDValue OutChains[6]; 8415 8416 // Large code-model. 8417 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode. 8418 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode. 8419 8420 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10); 8421 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11); 8422 8423 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix 8424 8425 // Load the pointer to the nested function into R11. 8426 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11 8427 SDValue Addr = Trmp; 8428 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 8429 Addr, MachinePointerInfo(TrmpAddr), 8430 false, false, 0); 8431 8432 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8433 DAG.getConstant(2, MVT::i64)); 8434 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, 8435 MachinePointerInfo(TrmpAddr, 2), 8436 false, false, 2); 8437 8438 // Load the 'nest' parameter value into R10. 8439 // R10 is specified in X86CallingConv.td 8440 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10 8441 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8442 DAG.getConstant(10, MVT::i64)); 8443 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 8444 Addr, MachinePointerInfo(TrmpAddr, 10), 8445 false, false, 0); 8446 8447 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8448 DAG.getConstant(12, MVT::i64)); 8449 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, 8450 MachinePointerInfo(TrmpAddr, 12), 8451 false, false, 2); 8452 8453 // Jump to the nested function. 8454 OpCode = (JMP64r << 8) | REX_WB; // jmpq *... 8455 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8456 DAG.getConstant(20, MVT::i64)); 8457 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 8458 Addr, MachinePointerInfo(TrmpAddr, 20), 8459 false, false, 0); 8460 8461 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11 8462 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8463 DAG.getConstant(22, MVT::i64)); 8464 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr, 8465 MachinePointerInfo(TrmpAddr, 22), 8466 false, false, 0); 8467 8468 SDValue Ops[] = 8469 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) }; 8470 return DAG.getMergeValues(Ops, 2, dl); 8471 } else { 8472 const Function *Func = 8473 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue()); 8474 CallingConv::ID CC = Func->getCallingConv(); 8475 unsigned NestReg; 8476 8477 switch (CC) { 8478 default: 8479 llvm_unreachable("Unsupported calling convention"); 8480 case CallingConv::C: 8481 case CallingConv::X86_StdCall: { 8482 // Pass 'nest' parameter in ECX. 8483 // Must be kept in sync with X86CallingConv.td 8484 NestReg = X86::ECX; 8485 8486 // Check that ECX wasn't needed by an 'inreg' parameter. 8487 const FunctionType *FTy = Func->getFunctionType(); 8488 const AttrListPtr &Attrs = Func->getAttributes(); 8489 8490 if (!Attrs.isEmpty() && !Func->isVarArg()) { 8491 unsigned InRegCount = 0; 8492 unsigned Idx = 1; 8493 8494 for (FunctionType::param_iterator I = FTy->param_begin(), 8495 E = FTy->param_end(); I != E; ++I, ++Idx) 8496 if (Attrs.paramHasAttr(Idx, Attribute::InReg)) 8497 // FIXME: should only count parameters that are lowered to integers. 8498 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32; 8499 8500 if (InRegCount > 2) { 8501 report_fatal_error("Nest register in use - reduce number of inreg" 8502 " parameters!"); 8503 } 8504 } 8505 break; 8506 } 8507 case CallingConv::X86_FastCall: 8508 case CallingConv::X86_ThisCall: 8509 case CallingConv::Fast: 8510 // Pass 'nest' parameter in EAX. 8511 // Must be kept in sync with X86CallingConv.td 8512 NestReg = X86::EAX; 8513 break; 8514 } 8515 8516 SDValue OutChains[4]; 8517 SDValue Addr, Disp; 8518 8519 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8520 DAG.getConstant(10, MVT::i32)); 8521 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr); 8522 8523 // This is storing the opcode for MOV32ri. 8524 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte. 8525 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg); 8526 OutChains[0] = DAG.getStore(Root, dl, 8527 DAG.getConstant(MOV32ri|N86Reg, MVT::i8), 8528 Trmp, MachinePointerInfo(TrmpAddr), 8529 false, false, 0); 8530 8531 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8532 DAG.getConstant(1, MVT::i32)); 8533 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, 8534 MachinePointerInfo(TrmpAddr, 1), 8535 false, false, 1); 8536 8537 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode. 8538 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8539 DAG.getConstant(5, MVT::i32)); 8540 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr, 8541 MachinePointerInfo(TrmpAddr, 5), 8542 false, false, 1); 8543 8544 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8545 DAG.getConstant(6, MVT::i32)); 8546 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, 8547 MachinePointerInfo(TrmpAddr, 6), 8548 false, false, 1); 8549 8550 SDValue Ops[] = 8551 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) }; 8552 return DAG.getMergeValues(Ops, 2, dl); 8553 } 8554} 8555 8556SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8557 SelectionDAG &DAG) const { 8558 /* 8559 The rounding mode is in bits 11:10 of FPSR, and has the following 8560 settings: 8561 00 Round to nearest 8562 01 Round to -inf 8563 10 Round to +inf 8564 11 Round to 0 8565 8566 FLT_ROUNDS, on the other hand, expects the following: 8567 -1 Undefined 8568 0 Round to 0 8569 1 Round to nearest 8570 2 Round to +inf 8571 3 Round to -inf 8572 8573 To perform the conversion, we do: 8574 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3) 8575 */ 8576 8577 MachineFunction &MF = DAG.getMachineFunction(); 8578 const TargetMachine &TM = MF.getTarget(); 8579 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 8580 unsigned StackAlignment = TFI.getStackAlignment(); 8581 EVT VT = Op.getValueType(); 8582 DebugLoc DL = Op.getDebugLoc(); 8583 8584 // Save FP Control Word to stack slot 8585 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false); 8586 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8587 8588 8589 MachineMemOperand *MMO = 8590 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8591 MachineMemOperand::MOStore, 2, 2); 8592 8593 SDValue Ops[] = { DAG.getEntryNode(), StackSlot }; 8594 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL, 8595 DAG.getVTList(MVT::Other), 8596 Ops, 2, MVT::i16, MMO); 8597 8598 // Load FP Control Word from stack slot 8599 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, 8600 MachinePointerInfo(), false, false, 0); 8601 8602 // Transform as necessary 8603 SDValue CWD1 = 8604 DAG.getNode(ISD::SRL, DL, MVT::i16, 8605 DAG.getNode(ISD::AND, DL, MVT::i16, 8606 CWD, DAG.getConstant(0x800, MVT::i16)), 8607 DAG.getConstant(11, MVT::i8)); 8608 SDValue CWD2 = 8609 DAG.getNode(ISD::SRL, DL, MVT::i16, 8610 DAG.getNode(ISD::AND, DL, MVT::i16, 8611 CWD, DAG.getConstant(0x400, MVT::i16)), 8612 DAG.getConstant(9, MVT::i8)); 8613 8614 SDValue RetVal = 8615 DAG.getNode(ISD::AND, DL, MVT::i16, 8616 DAG.getNode(ISD::ADD, DL, MVT::i16, 8617 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2), 8618 DAG.getConstant(1, MVT::i16)), 8619 DAG.getConstant(3, MVT::i16)); 8620 8621 8622 return DAG.getNode((VT.getSizeInBits() < 16 ? 8623 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal); 8624} 8625 8626SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const { 8627 EVT VT = Op.getValueType(); 8628 EVT OpVT = VT; 8629 unsigned NumBits = VT.getSizeInBits(); 8630 DebugLoc dl = Op.getDebugLoc(); 8631 8632 Op = Op.getOperand(0); 8633 if (VT == MVT::i8) { 8634 // Zero extend to i32 since there is not an i8 bsr. 8635 OpVT = MVT::i32; 8636 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 8637 } 8638 8639 // Issue a bsr (scan bits in reverse) which also sets EFLAGS. 8640 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 8641 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 8642 8643 // If src is zero (i.e. bsr sets ZF), returns NumBits. 8644 SDValue Ops[] = { 8645 Op, 8646 DAG.getConstant(NumBits+NumBits-1, OpVT), 8647 DAG.getConstant(X86::COND_E, MVT::i8), 8648 Op.getValue(1) 8649 }; 8650 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 8651 8652 // Finally xor with NumBits-1. 8653 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 8654 8655 if (VT == MVT::i8) 8656 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 8657 return Op; 8658} 8659 8660SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const { 8661 EVT VT = Op.getValueType(); 8662 EVT OpVT = VT; 8663 unsigned NumBits = VT.getSizeInBits(); 8664 DebugLoc dl = Op.getDebugLoc(); 8665 8666 Op = Op.getOperand(0); 8667 if (VT == MVT::i8) { 8668 OpVT = MVT::i32; 8669 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 8670 } 8671 8672 // Issue a bsf (scan bits forward) which also sets EFLAGS. 8673 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 8674 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); 8675 8676 // If src is zero (i.e. bsf sets ZF), returns NumBits. 8677 SDValue Ops[] = { 8678 Op, 8679 DAG.getConstant(NumBits, OpVT), 8680 DAG.getConstant(X86::COND_E, MVT::i8), 8681 Op.getValue(1) 8682 }; 8683 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 8684 8685 if (VT == MVT::i8) 8686 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 8687 return Op; 8688} 8689 8690SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const { 8691 EVT VT = Op.getValueType(); 8692 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply"); 8693 DebugLoc dl = Op.getDebugLoc(); 8694 8695 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32); 8696 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32); 8697 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b ); 8698 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi ); 8699 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b ); 8700 // 8701 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 ); 8702 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 ); 8703 // return AloBlo + AloBhi + AhiBlo; 8704 8705 SDValue A = Op.getOperand(0); 8706 SDValue B = Op.getOperand(1); 8707 8708 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8709 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 8710 A, DAG.getConstant(32, MVT::i32)); 8711 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8712 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 8713 B, DAG.getConstant(32, MVT::i32)); 8714 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8715 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 8716 A, B); 8717 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8718 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 8719 A, Bhi); 8720 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8721 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 8722 Ahi, B); 8723 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8724 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 8725 AloBhi, DAG.getConstant(32, MVT::i32)); 8726 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8727 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 8728 AhiBlo, DAG.getConstant(32, MVT::i32)); 8729 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 8730 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 8731 return Res; 8732} 8733 8734SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const { 8735 EVT VT = Op.getValueType(); 8736 DebugLoc dl = Op.getDebugLoc(); 8737 SDValue R = Op.getOperand(0); 8738 8739 LLVMContext *Context = DAG.getContext(); 8740 8741 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later"); 8742 8743 if (VT == MVT::v4i32) { 8744 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8745 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 8746 Op.getOperand(1), DAG.getConstant(23, MVT::i32)); 8747 8748 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U)); 8749 8750 std::vector<Constant*> CV(4, CI); 8751 Constant *C = ConstantVector::get(CV); 8752 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8753 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8754 MachinePointerInfo::getConstantPool(), 8755 false, false, 16); 8756 8757 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend); 8758 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op); 8759 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op); 8760 return DAG.getNode(ISD::MUL, dl, VT, Op, R); 8761 } 8762 if (VT == MVT::v16i8) { 8763 // a = a << 5; 8764 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8765 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 8766 Op.getOperand(1), DAG.getConstant(5, MVT::i32)); 8767 8768 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15)); 8769 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63)); 8770 8771 std::vector<Constant*> CVM1(16, CM1); 8772 std::vector<Constant*> CVM2(16, CM2); 8773 Constant *C = ConstantVector::get(CVM1); 8774 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8775 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8776 MachinePointerInfo::getConstantPool(), 8777 false, false, 16); 8778 8779 // r = pblendv(r, psllw(r & (char16)15, 4), a); 8780 M = DAG.getNode(ISD::AND, dl, VT, R, M); 8781 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8782 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 8783 DAG.getConstant(4, MVT::i32)); 8784 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op); 8785 // a += a 8786 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 8787 8788 C = ConstantVector::get(CVM2); 8789 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8790 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8791 MachinePointerInfo::getConstantPool(), 8792 false, false, 16); 8793 8794 // r = pblendv(r, psllw(r & (char16)63, 2), a); 8795 M = DAG.getNode(ISD::AND, dl, VT, R, M); 8796 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8797 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 8798 DAG.getConstant(2, MVT::i32)); 8799 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op); 8800 // a += a 8801 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 8802 8803 // return pblendv(r, r+r, a); 8804 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, 8805 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op); 8806 return R; 8807 } 8808 return SDValue(); 8809} 8810 8811SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 8812 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus 8813 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering 8814 // looks for this combo and may remove the "setcc" instruction if the "setcc" 8815 // has only one use. 8816 SDNode *N = Op.getNode(); 8817 SDValue LHS = N->getOperand(0); 8818 SDValue RHS = N->getOperand(1); 8819 unsigned BaseOp = 0; 8820 unsigned Cond = 0; 8821 DebugLoc DL = Op.getDebugLoc(); 8822 switch (Op.getOpcode()) { 8823 default: llvm_unreachable("Unknown ovf instruction!"); 8824 case ISD::SADDO: 8825 // A subtract of one will be selected as a INC. Note that INC doesn't 8826 // set CF, so we can't do this for UADDO. 8827 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 8828 if (C->getAPIntValue() == 1) { 8829 BaseOp = X86ISD::INC; 8830 Cond = X86::COND_O; 8831 break; 8832 } 8833 BaseOp = X86ISD::ADD; 8834 Cond = X86::COND_O; 8835 break; 8836 case ISD::UADDO: 8837 BaseOp = X86ISD::ADD; 8838 Cond = X86::COND_B; 8839 break; 8840 case ISD::SSUBO: 8841 // A subtract of one will be selected as a DEC. Note that DEC doesn't 8842 // set CF, so we can't do this for USUBO. 8843 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 8844 if (C->getAPIntValue() == 1) { 8845 BaseOp = X86ISD::DEC; 8846 Cond = X86::COND_O; 8847 break; 8848 } 8849 BaseOp = X86ISD::SUB; 8850 Cond = X86::COND_O; 8851 break; 8852 case ISD::USUBO: 8853 BaseOp = X86ISD::SUB; 8854 Cond = X86::COND_B; 8855 break; 8856 case ISD::SMULO: 8857 BaseOp = X86ISD::SMUL; 8858 Cond = X86::COND_O; 8859 break; 8860 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs 8861 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0), 8862 MVT::i32); 8863 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS); 8864 8865 SDValue SetCC = 8866 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 8867 DAG.getConstant(X86::COND_O, MVT::i32), 8868 SDValue(Sum.getNode(), 2)); 8869 8870 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC); 8871 return Sum; 8872 } 8873 } 8874 8875 // Also sets EFLAGS. 8876 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 8877 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 8878 8879 SDValue SetCC = 8880 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1), 8881 DAG.getConstant(Cond, MVT::i32), 8882 SDValue(Sum.getNode(), 1)); 8883 8884 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC); 8885 return Sum; 8886} 8887 8888SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{ 8889 DebugLoc dl = Op.getDebugLoc(); 8890 8891 if (!Subtarget->hasSSE2()) { 8892 SDValue Chain = Op.getOperand(0); 8893 SDValue Zero = DAG.getConstant(0, 8894 Subtarget->is64Bit() ? MVT::i64 : MVT::i32); 8895 SDValue Ops[] = { 8896 DAG.getRegister(X86::ESP, MVT::i32), // Base 8897 DAG.getTargetConstant(1, MVT::i8), // Scale 8898 DAG.getRegister(0, MVT::i32), // Index 8899 DAG.getTargetConstant(0, MVT::i32), // Disp 8900 DAG.getRegister(0, MVT::i32), // Segment. 8901 Zero, 8902 Chain 8903 }; 8904 SDNode *Res = 8905 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 8906 array_lengthof(Ops)); 8907 return SDValue(Res, 0); 8908 } 8909 8910 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 8911 if (!isDev) 8912 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 8913 8914 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8915 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8916 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 8917 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 8918 8919 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>; 8920 if (!Op1 && !Op2 && !Op3 && Op4) 8921 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0)); 8922 8923 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>; 8924 if (Op1 && !Op2 && !Op3 && !Op4) 8925 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0)); 8926 8927 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 8928 // (MFENCE)>; 8929 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 8930} 8931 8932SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8933 EVT T = Op.getValueType(); 8934 DebugLoc DL = Op.getDebugLoc(); 8935 unsigned Reg = 0; 8936 unsigned size = 0; 8937 switch(T.getSimpleVT().SimpleTy) { 8938 default: 8939 assert(false && "Invalid value type!"); 8940 case MVT::i8: Reg = X86::AL; size = 1; break; 8941 case MVT::i16: Reg = X86::AX; size = 2; break; 8942 case MVT::i32: Reg = X86::EAX; size = 4; break; 8943 case MVT::i64: 8944 assert(Subtarget->is64Bit() && "Node not type legal!"); 8945 Reg = X86::RAX; size = 8; 8946 break; 8947 } 8948 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg, 8949 Op.getOperand(2), SDValue()); 8950 SDValue Ops[] = { cpIn.getValue(0), 8951 Op.getOperand(1), 8952 Op.getOperand(3), 8953 DAG.getTargetConstant(size, MVT::i8), 8954 cpIn.getValue(1) }; 8955 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 8956 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand(); 8957 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys, 8958 Ops, 5, T, MMO); 8959 SDValue cpOut = 8960 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1)); 8961 return cpOut; 8962} 8963 8964SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op, 8965 SelectionDAG &DAG) const { 8966 assert(Subtarget->is64Bit() && "Result not type legalized?"); 8967 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 8968 SDValue TheChain = Op.getOperand(0); 8969 DebugLoc dl = Op.getDebugLoc(); 8970 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 8971 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1)); 8972 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64, 8973 rax.getValue(2)); 8974 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx, 8975 DAG.getConstant(32, MVT::i8)); 8976 SDValue Ops[] = { 8977 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp), 8978 rdx.getValue(1) 8979 }; 8980 return DAG.getMergeValues(Ops, 2, dl); 8981} 8982 8983SDValue X86TargetLowering::LowerBITCAST(SDValue Op, 8984 SelectionDAG &DAG) const { 8985 EVT SrcVT = Op.getOperand(0).getValueType(); 8986 EVT DstVT = Op.getValueType(); 8987 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() && 8988 Subtarget->hasMMX() && "Unexpected custom BITCAST"); 8989 assert((DstVT == MVT::i64 || 8990 (DstVT.isVector() && DstVT.getSizeInBits()==64)) && 8991 "Unexpected custom BITCAST"); 8992 // i64 <=> MMX conversions are Legal. 8993 if (SrcVT==MVT::i64 && DstVT.isVector()) 8994 return Op; 8995 if (DstVT==MVT::i64 && SrcVT.isVector()) 8996 return Op; 8997 // MMX <=> MMX conversions are Legal. 8998 if (SrcVT.isVector() && DstVT.isVector()) 8999 return Op; 9000 // All other conversions need to be expanded. 9001 return SDValue(); 9002} 9003 9004SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const { 9005 SDNode *Node = Op.getNode(); 9006 DebugLoc dl = Node->getDebugLoc(); 9007 EVT T = Node->getValueType(0); 9008 SDValue negOp = DAG.getNode(ISD::SUB, dl, T, 9009 DAG.getConstant(0, T), Node->getOperand(2)); 9010 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, 9011 cast<AtomicSDNode>(Node)->getMemoryVT(), 9012 Node->getOperand(0), 9013 Node->getOperand(1), negOp, 9014 cast<AtomicSDNode>(Node)->getSrcValue(), 9015 cast<AtomicSDNode>(Node)->getAlignment()); 9016} 9017 9018static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 9019 EVT VT = Op.getNode()->getValueType(0); 9020 9021 // Let legalize expand this if it isn't a legal type yet. 9022 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9023 return SDValue(); 9024 9025 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 9026 9027 unsigned Opc; 9028 bool ExtraOp = false; 9029 switch (Op.getOpcode()) { 9030 default: assert(0 && "Invalid code"); 9031 case ISD::ADDC: Opc = X86ISD::ADD; break; 9032 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break; 9033 case ISD::SUBC: Opc = X86ISD::SUB; break; 9034 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break; 9035 } 9036 9037 if (!ExtraOp) 9038 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 9039 Op.getOperand(1)); 9040 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 9041 Op.getOperand(1), Op.getOperand(2)); 9042} 9043 9044/// LowerOperation - Provide custom lowering hooks for some operations. 9045/// 9046SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9047 switch (Op.getOpcode()) { 9048 default: llvm_unreachable("Should not custom lower this!"); 9049 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG); 9050 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG); 9051 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG); 9052 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9053 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 9054 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9055 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9056 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9057 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG); 9058 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG); 9059 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9060 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9061 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9062 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9063 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); 9064 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9065 case ISD::SHL_PARTS: 9066 case ISD::SRA_PARTS: 9067 case ISD::SRL_PARTS: return LowerShift(Op, DAG); 9068 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 9069 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG); 9070 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 9071 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG); 9072 case ISD::FABS: return LowerFABS(Op, DAG); 9073 case ISD::FNEG: return LowerFNEG(Op, DAG); 9074 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9075 case ISD::SETCC: return LowerSETCC(Op, DAG); 9076 case ISD::VSETCC: return LowerVSETCC(Op, DAG); 9077 case ISD::SELECT: return LowerSELECT(Op, DAG); 9078 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9079 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9080 case ISD::VASTART: return LowerVASTART(Op, DAG); 9081 case ISD::VAARG: return LowerVAARG(Op, DAG); 9082 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9083 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9084 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9085 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9086 case ISD::FRAME_TO_ARGS_OFFSET: 9087 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG); 9088 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9089 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG); 9090 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG); 9091 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9092 case ISD::CTLZ: return LowerCTLZ(Op, DAG); 9093 case ISD::CTTZ: return LowerCTTZ(Op, DAG); 9094 case ISD::MUL: return LowerMUL_V2I64(Op, DAG); 9095 case ISD::SHL: return LowerSHL(Op, DAG); 9096 case ISD::SADDO: 9097 case ISD::UADDO: 9098 case ISD::SSUBO: 9099 case ISD::USUBO: 9100 case ISD::SMULO: 9101 case ISD::UMULO: return LowerXALUO(Op, DAG); 9102 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG); 9103 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9104 case ISD::ADDC: 9105 case ISD::ADDE: 9106 case ISD::SUBC: 9107 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 9108 } 9109} 9110 9111void X86TargetLowering:: 9112ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results, 9113 SelectionDAG &DAG, unsigned NewOp) const { 9114 EVT T = Node->getValueType(0); 9115 DebugLoc dl = Node->getDebugLoc(); 9116 assert (T == MVT::i64 && "Only know how to expand i64 atomics"); 9117 9118 SDValue Chain = Node->getOperand(0); 9119 SDValue In1 = Node->getOperand(1); 9120 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9121 Node->getOperand(2), DAG.getIntPtrConstant(0)); 9122 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9123 Node->getOperand(2), DAG.getIntPtrConstant(1)); 9124 SDValue Ops[] = { Chain, In1, In2L, In2H }; 9125 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9126 SDValue Result = 9127 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64, 9128 cast<MemSDNode>(Node)->getMemOperand()); 9129 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)}; 9130 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 9131 Results.push_back(Result.getValue(2)); 9132} 9133 9134/// ReplaceNodeResults - Replace a node with an illegal result type 9135/// with a new node built out of custom code. 9136void X86TargetLowering::ReplaceNodeResults(SDNode *N, 9137 SmallVectorImpl<SDValue>&Results, 9138 SelectionDAG &DAG) const { 9139 DebugLoc dl = N->getDebugLoc(); 9140 switch (N->getOpcode()) { 9141 default: 9142 assert(false && "Do not know how to custom type legalize this operation!"); 9143 return; 9144 case ISD::ADDC: 9145 case ISD::ADDE: 9146 case ISD::SUBC: 9147 case ISD::SUBE: 9148 // We don't want to expand or promote these. 9149 return; 9150 case ISD::FP_TO_SINT: { 9151 std::pair<SDValue,SDValue> Vals = 9152 FP_TO_INTHelper(SDValue(N, 0), DAG, true); 9153 SDValue FIST = Vals.first, StackSlot = Vals.second; 9154 if (FIST.getNode() != 0) { 9155 EVT VT = N->getValueType(0); 9156 // Return a load from the stack slot. 9157 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, 9158 MachinePointerInfo(), false, false, 0)); 9159 } 9160 return; 9161 } 9162 case ISD::READCYCLECOUNTER: { 9163 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 9164 SDValue TheChain = N->getOperand(0); 9165 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 9166 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32, 9167 rd.getValue(1)); 9168 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32, 9169 eax.getValue(2)); 9170 // Use a buildpair to merge the two 32-bit values into a 64-bit one. 9171 SDValue Ops[] = { eax, edx }; 9172 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2)); 9173 Results.push_back(edx.getValue(1)); 9174 return; 9175 } 9176 case ISD::ATOMIC_CMP_SWAP: { 9177 EVT T = N->getValueType(0); 9178 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap"); 9179 SDValue cpInL, cpInH; 9180 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2), 9181 DAG.getConstant(0, MVT::i32)); 9182 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2), 9183 DAG.getConstant(1, MVT::i32)); 9184 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue()); 9185 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH, 9186 cpInL.getValue(1)); 9187 SDValue swapInL, swapInH; 9188 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3), 9189 DAG.getConstant(0, MVT::i32)); 9190 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3), 9191 DAG.getConstant(1, MVT::i32)); 9192 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL, 9193 cpInH.getValue(1)); 9194 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH, 9195 swapInL.getValue(1)); 9196 SDValue Ops[] = { swapInH.getValue(0), 9197 N->getOperand(1), 9198 swapInH.getValue(1) }; 9199 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 9200 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 9201 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, 9202 Ops, 3, T, MMO); 9203 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX, 9204 MVT::i32, Result.getValue(1)); 9205 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX, 9206 MVT::i32, cpOutL.getValue(2)); 9207 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)}; 9208 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 9209 Results.push_back(cpOutH.getValue(1)); 9210 return; 9211 } 9212 case ISD::ATOMIC_LOAD_ADD: 9213 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG); 9214 return; 9215 case ISD::ATOMIC_LOAD_AND: 9216 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG); 9217 return; 9218 case ISD::ATOMIC_LOAD_NAND: 9219 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG); 9220 return; 9221 case ISD::ATOMIC_LOAD_OR: 9222 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG); 9223 return; 9224 case ISD::ATOMIC_LOAD_SUB: 9225 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG); 9226 return; 9227 case ISD::ATOMIC_LOAD_XOR: 9228 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG); 9229 return; 9230 case ISD::ATOMIC_SWAP: 9231 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG); 9232 return; 9233 } 9234} 9235 9236const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const { 9237 switch (Opcode) { 9238 default: return NULL; 9239 case X86ISD::BSF: return "X86ISD::BSF"; 9240 case X86ISD::BSR: return "X86ISD::BSR"; 9241 case X86ISD::SHLD: return "X86ISD::SHLD"; 9242 case X86ISD::SHRD: return "X86ISD::SHRD"; 9243 case X86ISD::FAND: return "X86ISD::FAND"; 9244 case X86ISD::FOR: return "X86ISD::FOR"; 9245 case X86ISD::FXOR: return "X86ISD::FXOR"; 9246 case X86ISD::FSRL: return "X86ISD::FSRL"; 9247 case X86ISD::FILD: return "X86ISD::FILD"; 9248 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG"; 9249 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM"; 9250 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM"; 9251 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM"; 9252 case X86ISD::FLD: return "X86ISD::FLD"; 9253 case X86ISD::FST: return "X86ISD::FST"; 9254 case X86ISD::CALL: return "X86ISD::CALL"; 9255 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG"; 9256 case X86ISD::BT: return "X86ISD::BT"; 9257 case X86ISD::CMP: return "X86ISD::CMP"; 9258 case X86ISD::COMI: return "X86ISD::COMI"; 9259 case X86ISD::UCOMI: return "X86ISD::UCOMI"; 9260 case X86ISD::SETCC: return "X86ISD::SETCC"; 9261 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY"; 9262 case X86ISD::CMOV: return "X86ISD::CMOV"; 9263 case X86ISD::BRCOND: return "X86ISD::BRCOND"; 9264 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG"; 9265 case X86ISD::REP_STOS: return "X86ISD::REP_STOS"; 9266 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS"; 9267 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg"; 9268 case X86ISD::Wrapper: return "X86ISD::Wrapper"; 9269 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP"; 9270 case X86ISD::PEXTRB: return "X86ISD::PEXTRB"; 9271 case X86ISD::PEXTRW: return "X86ISD::PEXTRW"; 9272 case X86ISD::INSERTPS: return "X86ISD::INSERTPS"; 9273 case X86ISD::PINSRB: return "X86ISD::PINSRB"; 9274 case X86ISD::PINSRW: return "X86ISD::PINSRW"; 9275 case X86ISD::PSHUFB: return "X86ISD::PSHUFB"; 9276 case X86ISD::PANDN: return "X86ISD::PANDN"; 9277 case X86ISD::PSIGNB: return "X86ISD::PSIGNB"; 9278 case X86ISD::PSIGNW: return "X86ISD::PSIGNW"; 9279 case X86ISD::PSIGND: return "X86ISD::PSIGND"; 9280 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB"; 9281 case X86ISD::FMAX: return "X86ISD::FMAX"; 9282 case X86ISD::FMIN: return "X86ISD::FMIN"; 9283 case X86ISD::FRSQRT: return "X86ISD::FRSQRT"; 9284 case X86ISD::FRCP: return "X86ISD::FRCP"; 9285 case X86ISD::TLSADDR: return "X86ISD::TLSADDR"; 9286 case X86ISD::TLSCALL: return "X86ISD::TLSCALL"; 9287 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN"; 9288 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN"; 9289 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m"; 9290 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG"; 9291 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG"; 9292 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG"; 9293 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG"; 9294 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG"; 9295 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG"; 9296 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG"; 9297 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG"; 9298 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL"; 9299 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD"; 9300 case X86ISD::VSHL: return "X86ISD::VSHL"; 9301 case X86ISD::VSRL: return "X86ISD::VSRL"; 9302 case X86ISD::CMPPD: return "X86ISD::CMPPD"; 9303 case X86ISD::CMPPS: return "X86ISD::CMPPS"; 9304 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB"; 9305 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW"; 9306 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD"; 9307 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ"; 9308 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB"; 9309 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW"; 9310 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD"; 9311 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ"; 9312 case X86ISD::ADD: return "X86ISD::ADD"; 9313 case X86ISD::SUB: return "X86ISD::SUB"; 9314 case X86ISD::ADC: return "X86ISD::ADC"; 9315 case X86ISD::SBB: return "X86ISD::SBB"; 9316 case X86ISD::SMUL: return "X86ISD::SMUL"; 9317 case X86ISD::UMUL: return "X86ISD::UMUL"; 9318 case X86ISD::INC: return "X86ISD::INC"; 9319 case X86ISD::DEC: return "X86ISD::DEC"; 9320 case X86ISD::OR: return "X86ISD::OR"; 9321 case X86ISD::XOR: return "X86ISD::XOR"; 9322 case X86ISD::AND: return "X86ISD::AND"; 9323 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM"; 9324 case X86ISD::PTEST: return "X86ISD::PTEST"; 9325 case X86ISD::TESTP: return "X86ISD::TESTP"; 9326 case X86ISD::PALIGN: return "X86ISD::PALIGN"; 9327 case X86ISD::PSHUFD: return "X86ISD::PSHUFD"; 9328 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW"; 9329 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD"; 9330 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW"; 9331 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD"; 9332 case X86ISD::SHUFPS: return "X86ISD::SHUFPS"; 9333 case X86ISD::SHUFPD: return "X86ISD::SHUFPD"; 9334 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS"; 9335 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD"; 9336 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS"; 9337 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD"; 9338 case X86ISD::MOVLPS: return "X86ISD::MOVLPS"; 9339 case X86ISD::MOVLPD: return "X86ISD::MOVLPD"; 9340 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP"; 9341 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP"; 9342 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP"; 9343 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD"; 9344 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD"; 9345 case X86ISD::MOVSD: return "X86ISD::MOVSD"; 9346 case X86ISD::MOVSS: return "X86ISD::MOVSS"; 9347 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS"; 9348 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD"; 9349 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS"; 9350 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD"; 9351 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY"; 9352 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY"; 9353 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS"; 9354 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD"; 9355 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW"; 9356 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD"; 9357 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ"; 9358 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ"; 9359 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW"; 9360 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD"; 9361 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ"; 9362 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ"; 9363 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS"; 9364 case X86ISD::VAARG_64: return "X86ISD::VAARG_64"; 9365 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA"; 9366 } 9367} 9368 9369// isLegalAddressingMode - Return true if the addressing mode represented 9370// by AM is legal for this target, for a load/store of the specified type. 9371bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 9372 const Type *Ty) const { 9373 // X86 supports extremely general addressing modes. 9374 CodeModel::Model M = getTargetMachine().getCodeModel(); 9375 Reloc::Model R = getTargetMachine().getRelocationModel(); 9376 9377 // X86 allows a sign-extended 32-bit immediate field as a displacement. 9378 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL)) 9379 return false; 9380 9381 if (AM.BaseGV) { 9382 unsigned GVFlags = 9383 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine()); 9384 9385 // If a reference to this global requires an extra load, we can't fold it. 9386 if (isGlobalStubReference(GVFlags)) 9387 return false; 9388 9389 // If BaseGV requires a register for the PIC base, we cannot also have a 9390 // BaseReg specified. 9391 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags)) 9392 return false; 9393 9394 // If lower 4G is not available, then we must use rip-relative addressing. 9395 if ((M != CodeModel::Small || R != Reloc::Static) && 9396 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1)) 9397 return false; 9398 } 9399 9400 switch (AM.Scale) { 9401 case 0: 9402 case 1: 9403 case 2: 9404 case 4: 9405 case 8: 9406 // These scales always work. 9407 break; 9408 case 3: 9409 case 5: 9410 case 9: 9411 // These scales are formed with basereg+scalereg. Only accept if there is 9412 // no basereg yet. 9413 if (AM.HasBaseReg) 9414 return false; 9415 break; 9416 default: // Other stuff never works. 9417 return false; 9418 } 9419 9420 return true; 9421} 9422 9423 9424bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const { 9425 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 9426 return false; 9427 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 9428 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 9429 if (NumBits1 <= NumBits2) 9430 return false; 9431 return true; 9432} 9433 9434bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 9435 if (!VT1.isInteger() || !VT2.isInteger()) 9436 return false; 9437 unsigned NumBits1 = VT1.getSizeInBits(); 9438 unsigned NumBits2 = VT2.getSizeInBits(); 9439 if (NumBits1 <= NumBits2) 9440 return false; 9441 return true; 9442} 9443 9444bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const { 9445 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 9446 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit(); 9447} 9448 9449bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 9450 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 9451 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit(); 9452} 9453 9454bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const { 9455 // i16 instructions are longer (0x66 prefix) and potentially slower. 9456 return !(VT1 == MVT::i32 && VT2 == MVT::i16); 9457} 9458 9459/// isShuffleMaskLegal - Targets can use this to indicate that they only 9460/// support *some* VECTOR_SHUFFLE operations, those with specific masks. 9461/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 9462/// are assumed to be legal. 9463bool 9464X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 9465 EVT VT) const { 9466 // Very little shuffling can be done for 64-bit vectors right now. 9467 if (VT.getSizeInBits() == 64) 9468 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3()); 9469 9470 // FIXME: pshufb, blends, shifts. 9471 return (VT.getVectorNumElements() == 2 || 9472 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 9473 isMOVLMask(M, VT) || 9474 isSHUFPMask(M, VT) || 9475 isPSHUFDMask(M, VT) || 9476 isPSHUFHWMask(M, VT) || 9477 isPSHUFLWMask(M, VT) || 9478 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) || 9479 isUNPCKLMask(M, VT) || 9480 isUNPCKHMask(M, VT) || 9481 isUNPCKL_v_undef_Mask(M, VT) || 9482 isUNPCKH_v_undef_Mask(M, VT)); 9483} 9484 9485bool 9486X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 9487 EVT VT) const { 9488 unsigned NumElts = VT.getVectorNumElements(); 9489 // FIXME: This collection of masks seems suspect. 9490 if (NumElts == 2) 9491 return true; 9492 if (NumElts == 4 && VT.getSizeInBits() == 128) { 9493 return (isMOVLMask(Mask, VT) || 9494 isCommutedMOVLMask(Mask, VT, true) || 9495 isSHUFPMask(Mask, VT) || 9496 isCommutedSHUFPMask(Mask, VT)); 9497 } 9498 return false; 9499} 9500 9501//===----------------------------------------------------------------------===// 9502// X86 Scheduler Hooks 9503//===----------------------------------------------------------------------===// 9504 9505// private utility function 9506MachineBasicBlock * 9507X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr, 9508 MachineBasicBlock *MBB, 9509 unsigned regOpc, 9510 unsigned immOpc, 9511 unsigned LoadOpc, 9512 unsigned CXchgOpc, 9513 unsigned notOpc, 9514 unsigned EAXreg, 9515 TargetRegisterClass *RC, 9516 bool invSrc) const { 9517 // For the atomic bitwise operator, we generate 9518 // thisMBB: 9519 // newMBB: 9520 // ld t1 = [bitinstr.addr] 9521 // op t2 = t1, [bitinstr.val] 9522 // mov EAX = t1 9523 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 9524 // bz newMBB 9525 // fallthrough -->nextMBB 9526 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9527 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 9528 MachineFunction::iterator MBBIter = MBB; 9529 ++MBBIter; 9530 9531 /// First build the CFG 9532 MachineFunction *F = MBB->getParent(); 9533 MachineBasicBlock *thisMBB = MBB; 9534 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 9535 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 9536 F->insert(MBBIter, newMBB); 9537 F->insert(MBBIter, nextMBB); 9538 9539 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 9540 nextMBB->splice(nextMBB->begin(), thisMBB, 9541 llvm::next(MachineBasicBlock::iterator(bInstr)), 9542 thisMBB->end()); 9543 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 9544 9545 // Update thisMBB to fall through to newMBB 9546 thisMBB->addSuccessor(newMBB); 9547 9548 // newMBB jumps to itself and fall through to nextMBB 9549 newMBB->addSuccessor(nextMBB); 9550 newMBB->addSuccessor(newMBB); 9551 9552 // Insert instructions into newMBB based on incoming instruction 9553 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 && 9554 "unexpected number of operands"); 9555 DebugLoc dl = bInstr->getDebugLoc(); 9556 MachineOperand& destOper = bInstr->getOperand(0); 9557 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 9558 int numArgs = bInstr->getNumOperands() - 1; 9559 for (int i=0; i < numArgs; ++i) 9560 argOpers[i] = &bInstr->getOperand(i+1); 9561 9562 // x86 address has 4 operands: base, index, scale, and displacement 9563 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 9564 int valArgIndx = lastAddrIndx + 1; 9565 9566 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 9567 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1); 9568 for (int i=0; i <= lastAddrIndx; ++i) 9569 (*MIB).addOperand(*argOpers[i]); 9570 9571 unsigned tt = F->getRegInfo().createVirtualRegister(RC); 9572 if (invSrc) { 9573 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1); 9574 } 9575 else 9576 tt = t1; 9577 9578 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 9579 assert((argOpers[valArgIndx]->isReg() || 9580 argOpers[valArgIndx]->isImm()) && 9581 "invalid operand"); 9582 if (argOpers[valArgIndx]->isReg()) 9583 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2); 9584 else 9585 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2); 9586 MIB.addReg(tt); 9587 (*MIB).addOperand(*argOpers[valArgIndx]); 9588 9589 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg); 9590 MIB.addReg(t1); 9591 9592 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc)); 9593 for (int i=0; i <= lastAddrIndx; ++i) 9594 (*MIB).addOperand(*argOpers[i]); 9595 MIB.addReg(t2); 9596 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 9597 (*MIB).setMemRefs(bInstr->memoperands_begin(), 9598 bInstr->memoperands_end()); 9599 9600 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 9601 MIB.addReg(EAXreg); 9602 9603 // insert branch 9604 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 9605 9606 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 9607 return nextMBB; 9608} 9609 9610// private utility function: 64 bit atomics on 32 bit host. 9611MachineBasicBlock * 9612X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr, 9613 MachineBasicBlock *MBB, 9614 unsigned regOpcL, 9615 unsigned regOpcH, 9616 unsigned immOpcL, 9617 unsigned immOpcH, 9618 bool invSrc) const { 9619 // For the atomic bitwise operator, we generate 9620 // thisMBB (instructions are in pairs, except cmpxchg8b) 9621 // ld t1,t2 = [bitinstr.addr] 9622 // newMBB: 9623 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4) 9624 // op t5, t6 <- out1, out2, [bitinstr.val] 9625 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val]) 9626 // mov ECX, EBX <- t5, t6 9627 // mov EAX, EDX <- t1, t2 9628 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit] 9629 // mov t3, t4 <- EAX, EDX 9630 // bz newMBB 9631 // result in out1, out2 9632 // fallthrough -->nextMBB 9633 9634 const TargetRegisterClass *RC = X86::GR32RegisterClass; 9635 const unsigned LoadOpc = X86::MOV32rm; 9636 const unsigned NotOpc = X86::NOT32r; 9637 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9638 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 9639 MachineFunction::iterator MBBIter = MBB; 9640 ++MBBIter; 9641 9642 /// First build the CFG 9643 MachineFunction *F = MBB->getParent(); 9644 MachineBasicBlock *thisMBB = MBB; 9645 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 9646 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 9647 F->insert(MBBIter, newMBB); 9648 F->insert(MBBIter, nextMBB); 9649 9650 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 9651 nextMBB->splice(nextMBB->begin(), thisMBB, 9652 llvm::next(MachineBasicBlock::iterator(bInstr)), 9653 thisMBB->end()); 9654 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 9655 9656 // Update thisMBB to fall through to newMBB 9657 thisMBB->addSuccessor(newMBB); 9658 9659 // newMBB jumps to itself and fall through to nextMBB 9660 newMBB->addSuccessor(nextMBB); 9661 newMBB->addSuccessor(newMBB); 9662 9663 DebugLoc dl = bInstr->getDebugLoc(); 9664 // Insert instructions into newMBB based on incoming instruction 9665 // There are 8 "real" operands plus 9 implicit def/uses, ignored here. 9666 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 && 9667 "unexpected number of operands"); 9668 MachineOperand& dest1Oper = bInstr->getOperand(0); 9669 MachineOperand& dest2Oper = bInstr->getOperand(1); 9670 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 9671 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) { 9672 argOpers[i] = &bInstr->getOperand(i+2); 9673 9674 // We use some of the operands multiple times, so conservatively just 9675 // clear any kill flags that might be present. 9676 if (argOpers[i]->isReg() && argOpers[i]->isUse()) 9677 argOpers[i]->setIsKill(false); 9678 } 9679 9680 // x86 address has 5 operands: base, index, scale, displacement, and segment. 9681 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 9682 9683 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 9684 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1); 9685 for (int i=0; i <= lastAddrIndx; ++i) 9686 (*MIB).addOperand(*argOpers[i]); 9687 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 9688 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2); 9689 // add 4 to displacement. 9690 for (int i=0; i <= lastAddrIndx-2; ++i) 9691 (*MIB).addOperand(*argOpers[i]); 9692 MachineOperand newOp3 = *(argOpers[3]); 9693 if (newOp3.isImm()) 9694 newOp3.setImm(newOp3.getImm()+4); 9695 else 9696 newOp3.setOffset(newOp3.getOffset()+4); 9697 (*MIB).addOperand(newOp3); 9698 (*MIB).addOperand(*argOpers[lastAddrIndx]); 9699 9700 // t3/4 are defined later, at the bottom of the loop 9701 unsigned t3 = F->getRegInfo().createVirtualRegister(RC); 9702 unsigned t4 = F->getRegInfo().createVirtualRegister(RC); 9703 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg()) 9704 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB); 9705 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg()) 9706 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB); 9707 9708 // The subsequent operations should be using the destination registers of 9709 //the PHI instructions. 9710 if (invSrc) { 9711 t1 = F->getRegInfo().createVirtualRegister(RC); 9712 t2 = F->getRegInfo().createVirtualRegister(RC); 9713 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg()); 9714 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg()); 9715 } else { 9716 t1 = dest1Oper.getReg(); 9717 t2 = dest2Oper.getReg(); 9718 } 9719 9720 int valArgIndx = lastAddrIndx + 1; 9721 assert((argOpers[valArgIndx]->isReg() || 9722 argOpers[valArgIndx]->isImm()) && 9723 "invalid operand"); 9724 unsigned t5 = F->getRegInfo().createVirtualRegister(RC); 9725 unsigned t6 = F->getRegInfo().createVirtualRegister(RC); 9726 if (argOpers[valArgIndx]->isReg()) 9727 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5); 9728 else 9729 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5); 9730 if (regOpcL != X86::MOV32rr) 9731 MIB.addReg(t1); 9732 (*MIB).addOperand(*argOpers[valArgIndx]); 9733 assert(argOpers[valArgIndx + 1]->isReg() == 9734 argOpers[valArgIndx]->isReg()); 9735 assert(argOpers[valArgIndx + 1]->isImm() == 9736 argOpers[valArgIndx]->isImm()); 9737 if (argOpers[valArgIndx + 1]->isReg()) 9738 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6); 9739 else 9740 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6); 9741 if (regOpcH != X86::MOV32rr) 9742 MIB.addReg(t2); 9743 (*MIB).addOperand(*argOpers[valArgIndx + 1]); 9744 9745 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 9746 MIB.addReg(t1); 9747 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX); 9748 MIB.addReg(t2); 9749 9750 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX); 9751 MIB.addReg(t5); 9752 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX); 9753 MIB.addReg(t6); 9754 9755 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B)); 9756 for (int i=0; i <= lastAddrIndx; ++i) 9757 (*MIB).addOperand(*argOpers[i]); 9758 9759 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 9760 (*MIB).setMemRefs(bInstr->memoperands_begin(), 9761 bInstr->memoperands_end()); 9762 9763 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3); 9764 MIB.addReg(X86::EAX); 9765 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4); 9766 MIB.addReg(X86::EDX); 9767 9768 // insert branch 9769 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 9770 9771 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 9772 return nextMBB; 9773} 9774 9775// private utility function 9776MachineBasicBlock * 9777X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr, 9778 MachineBasicBlock *MBB, 9779 unsigned cmovOpc) const { 9780 // For the atomic min/max operator, we generate 9781 // thisMBB: 9782 // newMBB: 9783 // ld t1 = [min/max.addr] 9784 // mov t2 = [min/max.val] 9785 // cmp t1, t2 9786 // cmov[cond] t2 = t1 9787 // mov EAX = t1 9788 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 9789 // bz newMBB 9790 // fallthrough -->nextMBB 9791 // 9792 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9793 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 9794 MachineFunction::iterator MBBIter = MBB; 9795 ++MBBIter; 9796 9797 /// First build the CFG 9798 MachineFunction *F = MBB->getParent(); 9799 MachineBasicBlock *thisMBB = MBB; 9800 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 9801 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 9802 F->insert(MBBIter, newMBB); 9803 F->insert(MBBIter, nextMBB); 9804 9805 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 9806 nextMBB->splice(nextMBB->begin(), thisMBB, 9807 llvm::next(MachineBasicBlock::iterator(mInstr)), 9808 thisMBB->end()); 9809 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 9810 9811 // Update thisMBB to fall through to newMBB 9812 thisMBB->addSuccessor(newMBB); 9813 9814 // newMBB jumps to newMBB and fall through to nextMBB 9815 newMBB->addSuccessor(nextMBB); 9816 newMBB->addSuccessor(newMBB); 9817 9818 DebugLoc dl = mInstr->getDebugLoc(); 9819 // Insert instructions into newMBB based on incoming instruction 9820 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 && 9821 "unexpected number of operands"); 9822 MachineOperand& destOper = mInstr->getOperand(0); 9823 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 9824 int numArgs = mInstr->getNumOperands() - 1; 9825 for (int i=0; i < numArgs; ++i) 9826 argOpers[i] = &mInstr->getOperand(i+1); 9827 9828 // x86 address has 4 operands: base, index, scale, and displacement 9829 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 9830 int valArgIndx = lastAddrIndx + 1; 9831 9832 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 9833 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1); 9834 for (int i=0; i <= lastAddrIndx; ++i) 9835 (*MIB).addOperand(*argOpers[i]); 9836 9837 // We only support register and immediate values 9838 assert((argOpers[valArgIndx]->isReg() || 9839 argOpers[valArgIndx]->isImm()) && 9840 "invalid operand"); 9841 9842 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 9843 if (argOpers[valArgIndx]->isReg()) 9844 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2); 9845 else 9846 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2); 9847 (*MIB).addOperand(*argOpers[valArgIndx]); 9848 9849 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 9850 MIB.addReg(t1); 9851 9852 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr)); 9853 MIB.addReg(t1); 9854 MIB.addReg(t2); 9855 9856 // Generate movc 9857 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 9858 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3); 9859 MIB.addReg(t2); 9860 MIB.addReg(t1); 9861 9862 // Cmp and exchange if none has modified the memory location 9863 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32)); 9864 for (int i=0; i <= lastAddrIndx; ++i) 9865 (*MIB).addOperand(*argOpers[i]); 9866 MIB.addReg(t3); 9867 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 9868 (*MIB).setMemRefs(mInstr->memoperands_begin(), 9869 mInstr->memoperands_end()); 9870 9871 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 9872 MIB.addReg(X86::EAX); 9873 9874 // insert branch 9875 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 9876 9877 mInstr->eraseFromParent(); // The pseudo instruction is gone now. 9878 return nextMBB; 9879} 9880 9881// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8 9882// or XMM0_V32I8 in AVX all of this code can be replaced with that 9883// in the .td file. 9884MachineBasicBlock * 9885X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB, 9886 unsigned numArgs, bool memArg) const { 9887 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) && 9888 "Target must have SSE4.2 or AVX features enabled"); 9889 9890 DebugLoc dl = MI->getDebugLoc(); 9891 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9892 unsigned Opc; 9893 if (!Subtarget->hasAVX()) { 9894 if (memArg) 9895 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm; 9896 else 9897 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr; 9898 } else { 9899 if (memArg) 9900 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm; 9901 else 9902 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr; 9903 } 9904 9905 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 9906 for (unsigned i = 0; i < numArgs; ++i) { 9907 MachineOperand &Op = MI->getOperand(i+1); 9908 if (!(Op.isReg() && Op.isImplicit())) 9909 MIB.addOperand(Op); 9910 } 9911 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg()) 9912 .addReg(X86::XMM0); 9913 9914 MI->eraseFromParent(); 9915 return BB; 9916} 9917 9918MachineBasicBlock * 9919X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const { 9920 DebugLoc dl = MI->getDebugLoc(); 9921 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9922 9923 // Address into RAX/EAX, other two args into ECX, EDX. 9924 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 9925 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 9926 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg); 9927 for (int i = 0; i < X86::AddrNumOperands; ++i) 9928 MIB.addOperand(MI->getOperand(i)); 9929 9930 unsigned ValOps = X86::AddrNumOperands; 9931 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 9932 .addReg(MI->getOperand(ValOps).getReg()); 9933 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX) 9934 .addReg(MI->getOperand(ValOps+1).getReg()); 9935 9936 // The instruction doesn't actually take any operands though. 9937 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr)); 9938 9939 MI->eraseFromParent(); // The pseudo is gone now. 9940 return BB; 9941} 9942 9943MachineBasicBlock * 9944X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const { 9945 DebugLoc dl = MI->getDebugLoc(); 9946 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9947 9948 // First arg in ECX, the second in EAX. 9949 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 9950 .addReg(MI->getOperand(0).getReg()); 9951 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX) 9952 .addReg(MI->getOperand(1).getReg()); 9953 9954 // The instruction doesn't actually take any operands though. 9955 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr)); 9956 9957 MI->eraseFromParent(); // The pseudo is gone now. 9958 return BB; 9959} 9960 9961MachineBasicBlock * 9962X86TargetLowering::EmitVAARG64WithCustomInserter( 9963 MachineInstr *MI, 9964 MachineBasicBlock *MBB) const { 9965 // Emit va_arg instruction on X86-64. 9966 9967 // Operands to this pseudo-instruction: 9968 // 0 ) Output : destination address (reg) 9969 // 1-5) Input : va_list address (addr, i64mem) 9970 // 6 ) ArgSize : Size (in bytes) of vararg type 9971 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset 9972 // 8 ) Align : Alignment of type 9973 // 9 ) EFLAGS (implicit-def) 9974 9975 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!"); 9976 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands"); 9977 9978 unsigned DestReg = MI->getOperand(0).getReg(); 9979 MachineOperand &Base = MI->getOperand(1); 9980 MachineOperand &Scale = MI->getOperand(2); 9981 MachineOperand &Index = MI->getOperand(3); 9982 MachineOperand &Disp = MI->getOperand(4); 9983 MachineOperand &Segment = MI->getOperand(5); 9984 unsigned ArgSize = MI->getOperand(6).getImm(); 9985 unsigned ArgMode = MI->getOperand(7).getImm(); 9986 unsigned Align = MI->getOperand(8).getImm(); 9987 9988 // Memory Reference 9989 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"); 9990 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 9991 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 9992 9993 // Machine Information 9994 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9995 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9996 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64); 9997 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32); 9998 DebugLoc DL = MI->getDebugLoc(); 9999 10000 // struct va_list { 10001 // i32 gp_offset 10002 // i32 fp_offset 10003 // i64 overflow_area (address) 10004 // i64 reg_save_area (address) 10005 // } 10006 // sizeof(va_list) = 24 10007 // alignment(va_list) = 8 10008 10009 unsigned TotalNumIntRegs = 6; 10010 unsigned TotalNumXMMRegs = 8; 10011 bool UseGPOffset = (ArgMode == 1); 10012 bool UseFPOffset = (ArgMode == 2); 10013 unsigned MaxOffset = TotalNumIntRegs * 8 + 10014 (UseFPOffset ? TotalNumXMMRegs * 16 : 0); 10015 10016 /* Align ArgSize to a multiple of 8 */ 10017 unsigned ArgSizeA8 = (ArgSize + 7) & ~7; 10018 bool NeedsAlign = (Align > 8); 10019 10020 MachineBasicBlock *thisMBB = MBB; 10021 MachineBasicBlock *overflowMBB; 10022 MachineBasicBlock *offsetMBB; 10023 MachineBasicBlock *endMBB; 10024 10025 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB 10026 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB 10027 unsigned OffsetReg = 0; 10028 10029 if (!UseGPOffset && !UseFPOffset) { 10030 // If we only pull from the overflow region, we don't create a branch. 10031 // We don't need to alter control flow. 10032 OffsetDestReg = 0; // unused 10033 OverflowDestReg = DestReg; 10034 10035 offsetMBB = NULL; 10036 overflowMBB = thisMBB; 10037 endMBB = thisMBB; 10038 } else { 10039 // First emit code to check if gp_offset (or fp_offset) is below the bound. 10040 // If so, pull the argument from reg_save_area. (branch to offsetMBB) 10041 // If not, pull from overflow_area. (branch to overflowMBB) 10042 // 10043 // thisMBB 10044 // | . 10045 // | . 10046 // offsetMBB overflowMBB 10047 // | . 10048 // | . 10049 // endMBB 10050 10051 // Registers for the PHI in endMBB 10052 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass); 10053 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass); 10054 10055 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 10056 MachineFunction *MF = MBB->getParent(); 10057 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10058 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10059 endMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10060 10061 MachineFunction::iterator MBBIter = MBB; 10062 ++MBBIter; 10063 10064 // Insert the new basic blocks 10065 MF->insert(MBBIter, offsetMBB); 10066 MF->insert(MBBIter, overflowMBB); 10067 MF->insert(MBBIter, endMBB); 10068 10069 // Transfer the remainder of MBB and its successor edges to endMBB. 10070 endMBB->splice(endMBB->begin(), thisMBB, 10071 llvm::next(MachineBasicBlock::iterator(MI)), 10072 thisMBB->end()); 10073 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 10074 10075 // Make offsetMBB and overflowMBB successors of thisMBB 10076 thisMBB->addSuccessor(offsetMBB); 10077 thisMBB->addSuccessor(overflowMBB); 10078 10079 // endMBB is a successor of both offsetMBB and overflowMBB 10080 offsetMBB->addSuccessor(endMBB); 10081 overflowMBB->addSuccessor(endMBB); 10082 10083 // Load the offset value into a register 10084 OffsetReg = MRI.createVirtualRegister(OffsetRegClass); 10085 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg) 10086 .addOperand(Base) 10087 .addOperand(Scale) 10088 .addOperand(Index) 10089 .addDisp(Disp, UseFPOffset ? 4 : 0) 10090 .addOperand(Segment) 10091 .setMemRefs(MMOBegin, MMOEnd); 10092 10093 // Check if there is enough room left to pull this argument. 10094 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri)) 10095 .addReg(OffsetReg) 10096 .addImm(MaxOffset + 8 - ArgSizeA8); 10097 10098 // Branch to "overflowMBB" if offset >= max 10099 // Fall through to "offsetMBB" otherwise 10100 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE))) 10101 .addMBB(overflowMBB); 10102 } 10103 10104 // In offsetMBB, emit code to use the reg_save_area. 10105 if (offsetMBB) { 10106 assert(OffsetReg != 0); 10107 10108 // Read the reg_save_area address. 10109 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass); 10110 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg) 10111 .addOperand(Base) 10112 .addOperand(Scale) 10113 .addOperand(Index) 10114 .addDisp(Disp, 16) 10115 .addOperand(Segment) 10116 .setMemRefs(MMOBegin, MMOEnd); 10117 10118 // Zero-extend the offset 10119 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass); 10120 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64) 10121 .addImm(0) 10122 .addReg(OffsetReg) 10123 .addImm(X86::sub_32bit); 10124 10125 // Add the offset to the reg_save_area to get the final address. 10126 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg) 10127 .addReg(OffsetReg64) 10128 .addReg(RegSaveReg); 10129 10130 // Compute the offset for the next argument 10131 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass); 10132 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg) 10133 .addReg(OffsetReg) 10134 .addImm(UseFPOffset ? 16 : 8); 10135 10136 // Store it back into the va_list. 10137 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr)) 10138 .addOperand(Base) 10139 .addOperand(Scale) 10140 .addOperand(Index) 10141 .addDisp(Disp, UseFPOffset ? 4 : 0) 10142 .addOperand(Segment) 10143 .addReg(NextOffsetReg) 10144 .setMemRefs(MMOBegin, MMOEnd); 10145 10146 // Jump to endMBB 10147 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4)) 10148 .addMBB(endMBB); 10149 } 10150 10151 // 10152 // Emit code to use overflow area 10153 // 10154 10155 // Load the overflow_area address into a register. 10156 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass); 10157 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg) 10158 .addOperand(Base) 10159 .addOperand(Scale) 10160 .addOperand(Index) 10161 .addDisp(Disp, 8) 10162 .addOperand(Segment) 10163 .setMemRefs(MMOBegin, MMOEnd); 10164 10165 // If we need to align it, do so. Otherwise, just copy the address 10166 // to OverflowDestReg. 10167 if (NeedsAlign) { 10168 // Align the overflow address 10169 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2"); 10170 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass); 10171 10172 // aligned_addr = (addr + (align-1)) & ~(align-1) 10173 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg) 10174 .addReg(OverflowAddrReg) 10175 .addImm(Align-1); 10176 10177 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg) 10178 .addReg(TmpReg) 10179 .addImm(~(uint64_t)(Align-1)); 10180 } else { 10181 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg) 10182 .addReg(OverflowAddrReg); 10183 } 10184 10185 // Compute the next overflow address after this argument. 10186 // (the overflow address should be kept 8-byte aligned) 10187 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass); 10188 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg) 10189 .addReg(OverflowDestReg) 10190 .addImm(ArgSizeA8); 10191 10192 // Store the new overflow address. 10193 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr)) 10194 .addOperand(Base) 10195 .addOperand(Scale) 10196 .addOperand(Index) 10197 .addDisp(Disp, 8) 10198 .addOperand(Segment) 10199 .addReg(NextAddrReg) 10200 .setMemRefs(MMOBegin, MMOEnd); 10201 10202 // If we branched, emit the PHI to the front of endMBB. 10203 if (offsetMBB) { 10204 BuildMI(*endMBB, endMBB->begin(), DL, 10205 TII->get(X86::PHI), DestReg) 10206 .addReg(OffsetDestReg).addMBB(offsetMBB) 10207 .addReg(OverflowDestReg).addMBB(overflowMBB); 10208 } 10209 10210 // Erase the pseudo instruction 10211 MI->eraseFromParent(); 10212 10213 return endMBB; 10214} 10215 10216MachineBasicBlock * 10217X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter( 10218 MachineInstr *MI, 10219 MachineBasicBlock *MBB) const { 10220 // Emit code to save XMM registers to the stack. The ABI says that the 10221 // number of registers to save is given in %al, so it's theoretically 10222 // possible to do an indirect jump trick to avoid saving all of them, 10223 // however this code takes a simpler approach and just executes all 10224 // of the stores if %al is non-zero. It's less code, and it's probably 10225 // easier on the hardware branch predictor, and stores aren't all that 10226 // expensive anyway. 10227 10228 // Create the new basic blocks. One block contains all the XMM stores, 10229 // and one block is the final destination regardless of whether any 10230 // stores were performed. 10231 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 10232 MachineFunction *F = MBB->getParent(); 10233 MachineFunction::iterator MBBIter = MBB; 10234 ++MBBIter; 10235 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB); 10236 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB); 10237 F->insert(MBBIter, XMMSaveMBB); 10238 F->insert(MBBIter, EndMBB); 10239 10240 // Transfer the remainder of MBB and its successor edges to EndMBB. 10241 EndMBB->splice(EndMBB->begin(), MBB, 10242 llvm::next(MachineBasicBlock::iterator(MI)), 10243 MBB->end()); 10244 EndMBB->transferSuccessorsAndUpdatePHIs(MBB); 10245 10246 // The original block will now fall through to the XMM save block. 10247 MBB->addSuccessor(XMMSaveMBB); 10248 // The XMMSaveMBB will fall through to the end block. 10249 XMMSaveMBB->addSuccessor(EndMBB); 10250 10251 // Now add the instructions. 10252 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10253 DebugLoc DL = MI->getDebugLoc(); 10254 10255 unsigned CountReg = MI->getOperand(0).getReg(); 10256 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm(); 10257 int64_t VarArgsFPOffset = MI->getOperand(2).getImm(); 10258 10259 if (!Subtarget->isTargetWin64()) { 10260 // If %al is 0, branch around the XMM save block. 10261 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg); 10262 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB); 10263 MBB->addSuccessor(EndMBB); 10264 } 10265 10266 // In the XMM save block, save all the XMM argument registers. 10267 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) { 10268 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset; 10269 MachineMemOperand *MMO = 10270 F->getMachineMemOperand( 10271 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset), 10272 MachineMemOperand::MOStore, 10273 /*Size=*/16, /*Align=*/16); 10274 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr)) 10275 .addFrameIndex(RegSaveFrameIndex) 10276 .addImm(/*Scale=*/1) 10277 .addReg(/*IndexReg=*/0) 10278 .addImm(/*Disp=*/Offset) 10279 .addReg(/*Segment=*/0) 10280 .addReg(MI->getOperand(i).getReg()) 10281 .addMemOperand(MMO); 10282 } 10283 10284 MI->eraseFromParent(); // The pseudo instruction is gone now. 10285 10286 return EndMBB; 10287} 10288 10289MachineBasicBlock * 10290X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, 10291 MachineBasicBlock *BB) const { 10292 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10293 DebugLoc DL = MI->getDebugLoc(); 10294 10295 // To "insert" a SELECT_CC instruction, we actually have to insert the 10296 // diamond control-flow pattern. The incoming instruction knows the 10297 // destination vreg to set, the condition code register to branch on, the 10298 // true/false values to select between, and a branch opcode to use. 10299 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10300 MachineFunction::iterator It = BB; 10301 ++It; 10302 10303 // thisMBB: 10304 // ... 10305 // TrueVal = ... 10306 // cmpTY ccX, r1, r2 10307 // bCC copy1MBB 10308 // fallthrough --> copy0MBB 10309 MachineBasicBlock *thisMBB = BB; 10310 MachineFunction *F = BB->getParent(); 10311 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10312 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10313 F->insert(It, copy0MBB); 10314 F->insert(It, sinkMBB); 10315 10316 // If the EFLAGS register isn't dead in the terminator, then claim that it's 10317 // live into the sink and copy blocks. 10318 const MachineFunction *MF = BB->getParent(); 10319 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo(); 10320 BitVector ReservedRegs = TRI->getReservedRegs(*MF); 10321 10322 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) { 10323 const MachineOperand &MO = MI->getOperand(I); 10324 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue; 10325 unsigned Reg = MO.getReg(); 10326 if (Reg != X86::EFLAGS) continue; 10327 copy0MBB->addLiveIn(Reg); 10328 sinkMBB->addLiveIn(Reg); 10329 } 10330 10331 // Transfer the remainder of BB and its successor edges to sinkMBB. 10332 sinkMBB->splice(sinkMBB->begin(), BB, 10333 llvm::next(MachineBasicBlock::iterator(MI)), 10334 BB->end()); 10335 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10336 10337 // Add the true and fallthrough blocks as its successors. 10338 BB->addSuccessor(copy0MBB); 10339 BB->addSuccessor(sinkMBB); 10340 10341 // Create the conditional branch instruction. 10342 unsigned Opc = 10343 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm()); 10344 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB); 10345 10346 // copy0MBB: 10347 // %FalseValue = ... 10348 // # fallthrough to sinkMBB 10349 copy0MBB->addSuccessor(sinkMBB); 10350 10351 // sinkMBB: 10352 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10353 // ... 10354 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10355 TII->get(X86::PHI), MI->getOperand(0).getReg()) 10356 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 10357 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 10358 10359 MI->eraseFromParent(); // The pseudo instruction is gone now. 10360 return sinkMBB; 10361} 10362 10363MachineBasicBlock * 10364X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI, 10365 MachineBasicBlock *BB) const { 10366 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10367 DebugLoc DL = MI->getDebugLoc(); 10368 10369 // The lowering is pretty easy: we're just emitting the call to _alloca. The 10370 // non-trivial part is impdef of ESP. 10371 // FIXME: The code should be tweaked as soon as we'll try to do codegen for 10372 // mingw-w64. 10373 10374 const char *StackProbeSymbol = 10375 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca"; 10376 10377 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32)) 10378 .addExternalSymbol(StackProbeSymbol) 10379 .addReg(X86::EAX, RegState::Implicit) 10380 .addReg(X86::ESP, RegState::Implicit) 10381 .addReg(X86::EAX, RegState::Define | RegState::Implicit) 10382 .addReg(X86::ESP, RegState::Define | RegState::Implicit) 10383 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 10384 10385 MI->eraseFromParent(); // The pseudo instruction is gone now. 10386 return BB; 10387} 10388 10389MachineBasicBlock * 10390X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI, 10391 MachineBasicBlock *BB) const { 10392 // This is pretty easy. We're taking the value that we received from 10393 // our load from the relocation, sticking it in either RDI (x86-64) 10394 // or EAX and doing an indirect call. The return value will then 10395 // be in the normal return register. 10396 const X86InstrInfo *TII 10397 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo()); 10398 DebugLoc DL = MI->getDebugLoc(); 10399 MachineFunction *F = BB->getParent(); 10400 10401 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?"); 10402 assert(MI->getOperand(3).isGlobal() && "This should be a global"); 10403 10404 if (Subtarget->is64Bit()) { 10405 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 10406 TII->get(X86::MOV64rm), X86::RDI) 10407 .addReg(X86::RIP) 10408 .addImm(0).addReg(0) 10409 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 10410 MI->getOperand(3).getTargetFlags()) 10411 .addReg(0); 10412 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m)); 10413 addDirectMem(MIB, X86::RDI); 10414 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) { 10415 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 10416 TII->get(X86::MOV32rm), X86::EAX) 10417 .addReg(0) 10418 .addImm(0).addReg(0) 10419 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 10420 MI->getOperand(3).getTargetFlags()) 10421 .addReg(0); 10422 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 10423 addDirectMem(MIB, X86::EAX); 10424 } else { 10425 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 10426 TII->get(X86::MOV32rm), X86::EAX) 10427 .addReg(TII->getGlobalBaseReg(F)) 10428 .addImm(0).addReg(0) 10429 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 10430 MI->getOperand(3).getTargetFlags()) 10431 .addReg(0); 10432 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 10433 addDirectMem(MIB, X86::EAX); 10434 } 10435 10436 MI->eraseFromParent(); // The pseudo instruction is gone now. 10437 return BB; 10438} 10439 10440MachineBasicBlock * 10441X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 10442 MachineBasicBlock *BB) const { 10443 switch (MI->getOpcode()) { 10444 default: assert(false && "Unexpected instr type to insert"); 10445 case X86::TAILJMPd64: 10446 case X86::TAILJMPr64: 10447 case X86::TAILJMPm64: 10448 assert(!"TAILJMP64 would not be touched here."); 10449 case X86::TCRETURNdi64: 10450 case X86::TCRETURNri64: 10451 case X86::TCRETURNmi64: 10452 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset. 10453 // On AMD64, additional defs should be added before register allocation. 10454 if (!Subtarget->isTargetWin64()) { 10455 MI->addRegisterDefined(X86::RSI); 10456 MI->addRegisterDefined(X86::RDI); 10457 MI->addRegisterDefined(X86::XMM6); 10458 MI->addRegisterDefined(X86::XMM7); 10459 MI->addRegisterDefined(X86::XMM8); 10460 MI->addRegisterDefined(X86::XMM9); 10461 MI->addRegisterDefined(X86::XMM10); 10462 MI->addRegisterDefined(X86::XMM11); 10463 MI->addRegisterDefined(X86::XMM12); 10464 MI->addRegisterDefined(X86::XMM13); 10465 MI->addRegisterDefined(X86::XMM14); 10466 MI->addRegisterDefined(X86::XMM15); 10467 } 10468 return BB; 10469 case X86::WIN_ALLOCA: 10470 return EmitLoweredWinAlloca(MI, BB); 10471 case X86::TLSCall_32: 10472 case X86::TLSCall_64: 10473 return EmitLoweredTLSCall(MI, BB); 10474 case X86::CMOV_GR8: 10475 case X86::CMOV_FR32: 10476 case X86::CMOV_FR64: 10477 case X86::CMOV_V4F32: 10478 case X86::CMOV_V2F64: 10479 case X86::CMOV_V2I64: 10480 case X86::CMOV_GR16: 10481 case X86::CMOV_GR32: 10482 case X86::CMOV_RFP32: 10483 case X86::CMOV_RFP64: 10484 case X86::CMOV_RFP80: 10485 return EmitLoweredSelect(MI, BB); 10486 10487 case X86::FP32_TO_INT16_IN_MEM: 10488 case X86::FP32_TO_INT32_IN_MEM: 10489 case X86::FP32_TO_INT64_IN_MEM: 10490 case X86::FP64_TO_INT16_IN_MEM: 10491 case X86::FP64_TO_INT32_IN_MEM: 10492 case X86::FP64_TO_INT64_IN_MEM: 10493 case X86::FP80_TO_INT16_IN_MEM: 10494 case X86::FP80_TO_INT32_IN_MEM: 10495 case X86::FP80_TO_INT64_IN_MEM: { 10496 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10497 DebugLoc DL = MI->getDebugLoc(); 10498 10499 // Change the floating point control register to use "round towards zero" 10500 // mode when truncating to an integer value. 10501 MachineFunction *F = BB->getParent(); 10502 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false); 10503 addFrameReference(BuildMI(*BB, MI, DL, 10504 TII->get(X86::FNSTCW16m)), CWFrameIdx); 10505 10506 // Load the old value of the high byte of the control word... 10507 unsigned OldCW = 10508 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass); 10509 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW), 10510 CWFrameIdx); 10511 10512 // Set the high part to be round to zero... 10513 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx) 10514 .addImm(0xC7F); 10515 10516 // Reload the modified control word now... 10517 addFrameReference(BuildMI(*BB, MI, DL, 10518 TII->get(X86::FLDCW16m)), CWFrameIdx); 10519 10520 // Restore the memory image of control word to original value 10521 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx) 10522 .addReg(OldCW); 10523 10524 // Get the X86 opcode to use. 10525 unsigned Opc; 10526 switch (MI->getOpcode()) { 10527 default: llvm_unreachable("illegal opcode!"); 10528 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break; 10529 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break; 10530 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break; 10531 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break; 10532 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break; 10533 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break; 10534 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break; 10535 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break; 10536 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break; 10537 } 10538 10539 X86AddressMode AM; 10540 MachineOperand &Op = MI->getOperand(0); 10541 if (Op.isReg()) { 10542 AM.BaseType = X86AddressMode::RegBase; 10543 AM.Base.Reg = Op.getReg(); 10544 } else { 10545 AM.BaseType = X86AddressMode::FrameIndexBase; 10546 AM.Base.FrameIndex = Op.getIndex(); 10547 } 10548 Op = MI->getOperand(1); 10549 if (Op.isImm()) 10550 AM.Scale = Op.getImm(); 10551 Op = MI->getOperand(2); 10552 if (Op.isImm()) 10553 AM.IndexReg = Op.getImm(); 10554 Op = MI->getOperand(3); 10555 if (Op.isGlobal()) { 10556 AM.GV = Op.getGlobal(); 10557 } else { 10558 AM.Disp = Op.getImm(); 10559 } 10560 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM) 10561 .addReg(MI->getOperand(X86::AddrNumOperands).getReg()); 10562 10563 // Reload the original control word now. 10564 addFrameReference(BuildMI(*BB, MI, DL, 10565 TII->get(X86::FLDCW16m)), CWFrameIdx); 10566 10567 MI->eraseFromParent(); // The pseudo instruction is gone now. 10568 return BB; 10569 } 10570 // String/text processing lowering. 10571 case X86::PCMPISTRM128REG: 10572 case X86::VPCMPISTRM128REG: 10573 return EmitPCMP(MI, BB, 3, false /* in-mem */); 10574 case X86::PCMPISTRM128MEM: 10575 case X86::VPCMPISTRM128MEM: 10576 return EmitPCMP(MI, BB, 3, true /* in-mem */); 10577 case X86::PCMPESTRM128REG: 10578 case X86::VPCMPESTRM128REG: 10579 return EmitPCMP(MI, BB, 5, false /* in mem */); 10580 case X86::PCMPESTRM128MEM: 10581 case X86::VPCMPESTRM128MEM: 10582 return EmitPCMP(MI, BB, 5, true /* in mem */); 10583 10584 // Thread synchronization. 10585 case X86::MONITOR: 10586 return EmitMonitor(MI, BB); 10587 case X86::MWAIT: 10588 return EmitMwait(MI, BB); 10589 10590 // Atomic Lowering. 10591 case X86::ATOMAND32: 10592 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 10593 X86::AND32ri, X86::MOV32rm, 10594 X86::LCMPXCHG32, 10595 X86::NOT32r, X86::EAX, 10596 X86::GR32RegisterClass); 10597 case X86::ATOMOR32: 10598 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 10599 X86::OR32ri, X86::MOV32rm, 10600 X86::LCMPXCHG32, 10601 X86::NOT32r, X86::EAX, 10602 X86::GR32RegisterClass); 10603 case X86::ATOMXOR32: 10604 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr, 10605 X86::XOR32ri, X86::MOV32rm, 10606 X86::LCMPXCHG32, 10607 X86::NOT32r, X86::EAX, 10608 X86::GR32RegisterClass); 10609 case X86::ATOMNAND32: 10610 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 10611 X86::AND32ri, X86::MOV32rm, 10612 X86::LCMPXCHG32, 10613 X86::NOT32r, X86::EAX, 10614 X86::GR32RegisterClass, true); 10615 case X86::ATOMMIN32: 10616 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr); 10617 case X86::ATOMMAX32: 10618 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr); 10619 case X86::ATOMUMIN32: 10620 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr); 10621 case X86::ATOMUMAX32: 10622 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr); 10623 10624 case X86::ATOMAND16: 10625 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 10626 X86::AND16ri, X86::MOV16rm, 10627 X86::LCMPXCHG16, 10628 X86::NOT16r, X86::AX, 10629 X86::GR16RegisterClass); 10630 case X86::ATOMOR16: 10631 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 10632 X86::OR16ri, X86::MOV16rm, 10633 X86::LCMPXCHG16, 10634 X86::NOT16r, X86::AX, 10635 X86::GR16RegisterClass); 10636 case X86::ATOMXOR16: 10637 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr, 10638 X86::XOR16ri, X86::MOV16rm, 10639 X86::LCMPXCHG16, 10640 X86::NOT16r, X86::AX, 10641 X86::GR16RegisterClass); 10642 case X86::ATOMNAND16: 10643 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 10644 X86::AND16ri, X86::MOV16rm, 10645 X86::LCMPXCHG16, 10646 X86::NOT16r, X86::AX, 10647 X86::GR16RegisterClass, true); 10648 case X86::ATOMMIN16: 10649 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr); 10650 case X86::ATOMMAX16: 10651 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr); 10652 case X86::ATOMUMIN16: 10653 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr); 10654 case X86::ATOMUMAX16: 10655 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr); 10656 10657 case X86::ATOMAND8: 10658 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 10659 X86::AND8ri, X86::MOV8rm, 10660 X86::LCMPXCHG8, 10661 X86::NOT8r, X86::AL, 10662 X86::GR8RegisterClass); 10663 case X86::ATOMOR8: 10664 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 10665 X86::OR8ri, X86::MOV8rm, 10666 X86::LCMPXCHG8, 10667 X86::NOT8r, X86::AL, 10668 X86::GR8RegisterClass); 10669 case X86::ATOMXOR8: 10670 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr, 10671 X86::XOR8ri, X86::MOV8rm, 10672 X86::LCMPXCHG8, 10673 X86::NOT8r, X86::AL, 10674 X86::GR8RegisterClass); 10675 case X86::ATOMNAND8: 10676 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 10677 X86::AND8ri, X86::MOV8rm, 10678 X86::LCMPXCHG8, 10679 X86::NOT8r, X86::AL, 10680 X86::GR8RegisterClass, true); 10681 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way. 10682 // This group is for 64-bit host. 10683 case X86::ATOMAND64: 10684 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 10685 X86::AND64ri32, X86::MOV64rm, 10686 X86::LCMPXCHG64, 10687 X86::NOT64r, X86::RAX, 10688 X86::GR64RegisterClass); 10689 case X86::ATOMOR64: 10690 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 10691 X86::OR64ri32, X86::MOV64rm, 10692 X86::LCMPXCHG64, 10693 X86::NOT64r, X86::RAX, 10694 X86::GR64RegisterClass); 10695 case X86::ATOMXOR64: 10696 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr, 10697 X86::XOR64ri32, X86::MOV64rm, 10698 X86::LCMPXCHG64, 10699 X86::NOT64r, X86::RAX, 10700 X86::GR64RegisterClass); 10701 case X86::ATOMNAND64: 10702 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 10703 X86::AND64ri32, X86::MOV64rm, 10704 X86::LCMPXCHG64, 10705 X86::NOT64r, X86::RAX, 10706 X86::GR64RegisterClass, true); 10707 case X86::ATOMMIN64: 10708 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr); 10709 case X86::ATOMMAX64: 10710 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr); 10711 case X86::ATOMUMIN64: 10712 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr); 10713 case X86::ATOMUMAX64: 10714 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr); 10715 10716 // This group does 64-bit operations on a 32-bit host. 10717 case X86::ATOMAND6432: 10718 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10719 X86::AND32rr, X86::AND32rr, 10720 X86::AND32ri, X86::AND32ri, 10721 false); 10722 case X86::ATOMOR6432: 10723 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10724 X86::OR32rr, X86::OR32rr, 10725 X86::OR32ri, X86::OR32ri, 10726 false); 10727 case X86::ATOMXOR6432: 10728 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10729 X86::XOR32rr, X86::XOR32rr, 10730 X86::XOR32ri, X86::XOR32ri, 10731 false); 10732 case X86::ATOMNAND6432: 10733 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10734 X86::AND32rr, X86::AND32rr, 10735 X86::AND32ri, X86::AND32ri, 10736 true); 10737 case X86::ATOMADD6432: 10738 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10739 X86::ADD32rr, X86::ADC32rr, 10740 X86::ADD32ri, X86::ADC32ri, 10741 false); 10742 case X86::ATOMSUB6432: 10743 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10744 X86::SUB32rr, X86::SBB32rr, 10745 X86::SUB32ri, X86::SBB32ri, 10746 false); 10747 case X86::ATOMSWAP6432: 10748 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10749 X86::MOV32rr, X86::MOV32rr, 10750 X86::MOV32ri, X86::MOV32ri, 10751 false); 10752 case X86::VASTART_SAVE_XMM_REGS: 10753 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB); 10754 10755 case X86::VAARG_64: 10756 return EmitVAARG64WithCustomInserter(MI, BB); 10757 } 10758} 10759 10760//===----------------------------------------------------------------------===// 10761// X86 Optimization Hooks 10762//===----------------------------------------------------------------------===// 10763 10764void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 10765 const APInt &Mask, 10766 APInt &KnownZero, 10767 APInt &KnownOne, 10768 const SelectionDAG &DAG, 10769 unsigned Depth) const { 10770 unsigned Opc = Op.getOpcode(); 10771 assert((Opc >= ISD::BUILTIN_OP_END || 10772 Opc == ISD::INTRINSIC_WO_CHAIN || 10773 Opc == ISD::INTRINSIC_W_CHAIN || 10774 Opc == ISD::INTRINSIC_VOID) && 10775 "Should use MaskedValueIsZero if you don't know whether Op" 10776 " is a target node!"); 10777 10778 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything. 10779 switch (Opc) { 10780 default: break; 10781 case X86ISD::ADD: 10782 case X86ISD::SUB: 10783 case X86ISD::ADC: 10784 case X86ISD::SBB: 10785 case X86ISD::SMUL: 10786 case X86ISD::UMUL: 10787 case X86ISD::INC: 10788 case X86ISD::DEC: 10789 case X86ISD::OR: 10790 case X86ISD::XOR: 10791 case X86ISD::AND: 10792 // These nodes' second result is a boolean. 10793 if (Op.getResNo() == 0) 10794 break; 10795 // Fallthrough 10796 case X86ISD::SETCC: 10797 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(), 10798 Mask.getBitWidth() - 1); 10799 break; 10800 } 10801} 10802 10803unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 10804 unsigned Depth) const { 10805 // SETCC_CARRY sets the dest to ~0 for true or 0 for false. 10806 if (Op.getOpcode() == X86ISD::SETCC_CARRY) 10807 return Op.getValueType().getScalarType().getSizeInBits(); 10808 10809 // Fallback case. 10810 return 1; 10811} 10812 10813/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 10814/// node is a GlobalAddress + offset. 10815bool X86TargetLowering::isGAPlusOffset(SDNode *N, 10816 const GlobalValue* &GA, 10817 int64_t &Offset) const { 10818 if (N->getOpcode() == X86ISD::Wrapper) { 10819 if (isa<GlobalAddressSDNode>(N->getOperand(0))) { 10820 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal(); 10821 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset(); 10822 return true; 10823 } 10824 } 10825 return TargetLowering::isGAPlusOffset(N, GA, Offset); 10826} 10827 10828/// PerformShuffleCombine - Combine a vector_shuffle that is equal to 10829/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load 10830/// if the load addresses are consecutive, non-overlapping, and in the right 10831/// order. 10832static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG, 10833 TargetLowering::DAGCombinerInfo &DCI) { 10834 DebugLoc dl = N->getDebugLoc(); 10835 EVT VT = N->getValueType(0); 10836 10837 if (VT.getSizeInBits() != 128) 10838 return SDValue(); 10839 10840 // Don't create instructions with illegal types after legalize types has run. 10841 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10842 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType())) 10843 return SDValue(); 10844 10845 SmallVector<SDValue, 16> Elts; 10846 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 10847 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0)); 10848 10849 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG); 10850} 10851 10852/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index 10853/// generation and convert it from being a bunch of shuffles and extracts 10854/// to a simple store and scalar loads to extract the elements. 10855static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG, 10856 const TargetLowering &TLI) { 10857 SDValue InputVector = N->getOperand(0); 10858 10859 // Only operate on vectors of 4 elements, where the alternative shuffling 10860 // gets to be more expensive. 10861 if (InputVector.getValueType() != MVT::v4i32) 10862 return SDValue(); 10863 10864 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a 10865 // single use which is a sign-extend or zero-extend, and all elements are 10866 // used. 10867 SmallVector<SDNode *, 4> Uses; 10868 unsigned ExtractedElements = 0; 10869 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(), 10870 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) { 10871 if (UI.getUse().getResNo() != InputVector.getResNo()) 10872 return SDValue(); 10873 10874 SDNode *Extract = *UI; 10875 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10876 return SDValue(); 10877 10878 if (Extract->getValueType(0) != MVT::i32) 10879 return SDValue(); 10880 if (!Extract->hasOneUse()) 10881 return SDValue(); 10882 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND && 10883 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND) 10884 return SDValue(); 10885 if (!isa<ConstantSDNode>(Extract->getOperand(1))) 10886 return SDValue(); 10887 10888 // Record which element was extracted. 10889 ExtractedElements |= 10890 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue(); 10891 10892 Uses.push_back(Extract); 10893 } 10894 10895 // If not all the elements were used, this may not be worthwhile. 10896 if (ExtractedElements != 15) 10897 return SDValue(); 10898 10899 // Ok, we've now decided to do the transformation. 10900 DebugLoc dl = InputVector.getDebugLoc(); 10901 10902 // Store the value to a temporary stack slot. 10903 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType()); 10904 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, 10905 MachinePointerInfo(), false, false, 0); 10906 10907 // Replace each use (extract) with a load of the appropriate element. 10908 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(), 10909 UE = Uses.end(); UI != UE; ++UI) { 10910 SDNode *Extract = *UI; 10911 10912 // Compute the element's address. 10913 SDValue Idx = Extract->getOperand(1); 10914 unsigned EltSize = 10915 InputVector.getValueType().getVectorElementType().getSizeInBits()/8; 10916 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(); 10917 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy()); 10918 10919 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), 10920 StackPtr, OffsetVal); 10921 10922 // Load the scalar. 10923 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, 10924 ScalarAddr, MachinePointerInfo(), 10925 false, false, 0); 10926 10927 // Replace the exact with the load. 10928 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar); 10929 } 10930 10931 // The replacement was made in place; don't return anything. 10932 return SDValue(); 10933} 10934 10935/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes. 10936static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG, 10937 const X86Subtarget *Subtarget) { 10938 DebugLoc DL = N->getDebugLoc(); 10939 SDValue Cond = N->getOperand(0); 10940 // Get the LHS/RHS of the select. 10941 SDValue LHS = N->getOperand(1); 10942 SDValue RHS = N->getOperand(2); 10943 10944 // If we have SSE[12] support, try to form min/max nodes. SSE min/max 10945 // instructions match the semantics of the common C idiom x<y?x:y but not 10946 // x<=y?x:y, because of how they handle negative zero (which can be 10947 // ignored in unsafe-math mode). 10948 if (Subtarget->hasSSE2() && 10949 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) && 10950 Cond.getOpcode() == ISD::SETCC) { 10951 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 10952 10953 unsigned Opcode = 0; 10954 // Check for x CC y ? x : y. 10955 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 10956 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 10957 switch (CC) { 10958 default: break; 10959 case ISD::SETULT: 10960 // Converting this to a min would handle NaNs incorrectly, and swapping 10961 // the operands would cause it to handle comparisons between positive 10962 // and negative zero incorrectly. 10963 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 10964 if (!UnsafeFPMath && 10965 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 10966 break; 10967 std::swap(LHS, RHS); 10968 } 10969 Opcode = X86ISD::FMIN; 10970 break; 10971 case ISD::SETOLE: 10972 // Converting this to a min would handle comparisons between positive 10973 // and negative zero incorrectly. 10974 if (!UnsafeFPMath && 10975 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 10976 break; 10977 Opcode = X86ISD::FMIN; 10978 break; 10979 case ISD::SETULE: 10980 // Converting this to a min would handle both negative zeros and NaNs 10981 // incorrectly, but we can swap the operands to fix both. 10982 std::swap(LHS, RHS); 10983 case ISD::SETOLT: 10984 case ISD::SETLT: 10985 case ISD::SETLE: 10986 Opcode = X86ISD::FMIN; 10987 break; 10988 10989 case ISD::SETOGE: 10990 // Converting this to a max would handle comparisons between positive 10991 // and negative zero incorrectly. 10992 if (!UnsafeFPMath && 10993 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS)) 10994 break; 10995 Opcode = X86ISD::FMAX; 10996 break; 10997 case ISD::SETUGT: 10998 // Converting this to a max would handle NaNs incorrectly, and swapping 10999 // the operands would cause it to handle comparisons between positive 11000 // and negative zero incorrectly. 11001 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 11002 if (!UnsafeFPMath && 11003 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 11004 break; 11005 std::swap(LHS, RHS); 11006 } 11007 Opcode = X86ISD::FMAX; 11008 break; 11009 case ISD::SETUGE: 11010 // Converting this to a max would handle both negative zeros and NaNs 11011 // incorrectly, but we can swap the operands to fix both. 11012 std::swap(LHS, RHS); 11013 case ISD::SETOGT: 11014 case ISD::SETGT: 11015 case ISD::SETGE: 11016 Opcode = X86ISD::FMAX; 11017 break; 11018 } 11019 // Check for x CC y ? y : x -- a min/max with reversed arms. 11020 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 11021 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 11022 switch (CC) { 11023 default: break; 11024 case ISD::SETOGE: 11025 // Converting this to a min would handle comparisons between positive 11026 // and negative zero incorrectly, and swapping the operands would 11027 // cause it to handle NaNs incorrectly. 11028 if (!UnsafeFPMath && 11029 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) { 11030 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 11031 break; 11032 std::swap(LHS, RHS); 11033 } 11034 Opcode = X86ISD::FMIN; 11035 break; 11036 case ISD::SETUGT: 11037 // Converting this to a min would handle NaNs incorrectly. 11038 if (!UnsafeFPMath && 11039 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) 11040 break; 11041 Opcode = X86ISD::FMIN; 11042 break; 11043 case ISD::SETUGE: 11044 // Converting this to a min would handle both negative zeros and NaNs 11045 // incorrectly, but we can swap the operands to fix both. 11046 std::swap(LHS, RHS); 11047 case ISD::SETOGT: 11048 case ISD::SETGT: 11049 case ISD::SETGE: 11050 Opcode = X86ISD::FMIN; 11051 break; 11052 11053 case ISD::SETULT: 11054 // Converting this to a max would handle NaNs incorrectly. 11055 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 11056 break; 11057 Opcode = X86ISD::FMAX; 11058 break; 11059 case ISD::SETOLE: 11060 // Converting this to a max would handle comparisons between positive 11061 // and negative zero incorrectly, and swapping the operands would 11062 // cause it to handle NaNs incorrectly. 11063 if (!UnsafeFPMath && 11064 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 11065 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 11066 break; 11067 std::swap(LHS, RHS); 11068 } 11069 Opcode = X86ISD::FMAX; 11070 break; 11071 case ISD::SETULE: 11072 // Converting this to a max would handle both negative zeros and NaNs 11073 // incorrectly, but we can swap the operands to fix both. 11074 std::swap(LHS, RHS); 11075 case ISD::SETOLT: 11076 case ISD::SETLT: 11077 case ISD::SETLE: 11078 Opcode = X86ISD::FMAX; 11079 break; 11080 } 11081 } 11082 11083 if (Opcode) 11084 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS); 11085 } 11086 11087 // If this is a select between two integer constants, try to do some 11088 // optimizations. 11089 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) { 11090 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS)) 11091 // Don't do this for crazy integer types. 11092 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) { 11093 // If this is efficiently invertible, canonicalize the LHSC/RHSC values 11094 // so that TrueC (the true value) is larger than FalseC. 11095 bool NeedsCondInvert = false; 11096 11097 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) && 11098 // Efficiently invertible. 11099 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible. 11100 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible. 11101 isa<ConstantSDNode>(Cond.getOperand(1))))) { 11102 NeedsCondInvert = true; 11103 std::swap(TrueC, FalseC); 11104 } 11105 11106 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0. 11107 if (FalseC->getAPIntValue() == 0 && 11108 TrueC->getAPIntValue().isPowerOf2()) { 11109 if (NeedsCondInvert) // Invert the condition if needed. 11110 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 11111 DAG.getConstant(1, Cond.getValueType())); 11112 11113 // Zero extend the condition if needed. 11114 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond); 11115 11116 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 11117 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond, 11118 DAG.getConstant(ShAmt, MVT::i8)); 11119 } 11120 11121 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. 11122 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 11123 if (NeedsCondInvert) // Invert the condition if needed. 11124 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 11125 DAG.getConstant(1, Cond.getValueType())); 11126 11127 // Zero extend the condition if needed. 11128 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 11129 FalseC->getValueType(0), Cond); 11130 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11131 SDValue(FalseC, 0)); 11132 } 11133 11134 // Optimize cases that will turn into an LEA instruction. This requires 11135 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 11136 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 11137 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 11138 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 11139 11140 bool isFastMultiplier = false; 11141 if (Diff < 10) { 11142 switch ((unsigned char)Diff) { 11143 default: break; 11144 case 1: // result = add base, cond 11145 case 2: // result = lea base( , cond*2) 11146 case 3: // result = lea base(cond, cond*2) 11147 case 4: // result = lea base( , cond*4) 11148 case 5: // result = lea base(cond, cond*4) 11149 case 8: // result = lea base( , cond*8) 11150 case 9: // result = lea base(cond, cond*8) 11151 isFastMultiplier = true; 11152 break; 11153 } 11154 } 11155 11156 if (isFastMultiplier) { 11157 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 11158 if (NeedsCondInvert) // Invert the condition if needed. 11159 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 11160 DAG.getConstant(1, Cond.getValueType())); 11161 11162 // Zero extend the condition if needed. 11163 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 11164 Cond); 11165 // Scale the condition by the difference. 11166 if (Diff != 1) 11167 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 11168 DAG.getConstant(Diff, Cond.getValueType())); 11169 11170 // Add the base if non-zero. 11171 if (FalseC->getAPIntValue() != 0) 11172 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11173 SDValue(FalseC, 0)); 11174 return Cond; 11175 } 11176 } 11177 } 11178 } 11179 11180 return SDValue(); 11181} 11182 11183/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL] 11184static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG, 11185 TargetLowering::DAGCombinerInfo &DCI) { 11186 DebugLoc DL = N->getDebugLoc(); 11187 11188 // If the flag operand isn't dead, don't touch this CMOV. 11189 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty()) 11190 return SDValue(); 11191 11192 // If this is a select between two integer constants, try to do some 11193 // optimizations. Note that the operands are ordered the opposite of SELECT 11194 // operands. 11195 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 11196 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 11197 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is 11198 // larger than FalseC (the false value). 11199 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2); 11200 11201 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) { 11202 CC = X86::GetOppositeBranchCondition(CC); 11203 std::swap(TrueC, FalseC); 11204 } 11205 11206 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0. 11207 // This is efficient for any integer data type (including i8/i16) and 11208 // shift amount. 11209 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) { 11210 SDValue Cond = N->getOperand(3); 11211 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 11212 DAG.getConstant(CC, MVT::i8), Cond); 11213 11214 // Zero extend the condition if needed. 11215 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond); 11216 11217 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 11218 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond, 11219 DAG.getConstant(ShAmt, MVT::i8)); 11220 if (N->getNumValues() == 2) // Dead flag value? 11221 return DCI.CombineTo(N, Cond, SDValue()); 11222 return Cond; 11223 } 11224 11225 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient 11226 // for any integer data type, including i8/i16. 11227 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 11228 SDValue Cond = N->getOperand(3); 11229 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 11230 DAG.getConstant(CC, MVT::i8), Cond); 11231 11232 // Zero extend the condition if needed. 11233 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 11234 FalseC->getValueType(0), Cond); 11235 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11236 SDValue(FalseC, 0)); 11237 11238 if (N->getNumValues() == 2) // Dead flag value? 11239 return DCI.CombineTo(N, Cond, SDValue()); 11240 return Cond; 11241 } 11242 11243 // Optimize cases that will turn into an LEA instruction. This requires 11244 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 11245 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 11246 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 11247 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 11248 11249 bool isFastMultiplier = false; 11250 if (Diff < 10) { 11251 switch ((unsigned char)Diff) { 11252 default: break; 11253 case 1: // result = add base, cond 11254 case 2: // result = lea base( , cond*2) 11255 case 3: // result = lea base(cond, cond*2) 11256 case 4: // result = lea base( , cond*4) 11257 case 5: // result = lea base(cond, cond*4) 11258 case 8: // result = lea base( , cond*8) 11259 case 9: // result = lea base(cond, cond*8) 11260 isFastMultiplier = true; 11261 break; 11262 } 11263 } 11264 11265 if (isFastMultiplier) { 11266 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 11267 SDValue Cond = N->getOperand(3); 11268 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 11269 DAG.getConstant(CC, MVT::i8), Cond); 11270 // Zero extend the condition if needed. 11271 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 11272 Cond); 11273 // Scale the condition by the difference. 11274 if (Diff != 1) 11275 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 11276 DAG.getConstant(Diff, Cond.getValueType())); 11277 11278 // Add the base if non-zero. 11279 if (FalseC->getAPIntValue() != 0) 11280 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11281 SDValue(FalseC, 0)); 11282 if (N->getNumValues() == 2) // Dead flag value? 11283 return DCI.CombineTo(N, Cond, SDValue()); 11284 return Cond; 11285 } 11286 } 11287 } 11288 } 11289 return SDValue(); 11290} 11291 11292 11293/// PerformMulCombine - Optimize a single multiply with constant into two 11294/// in order to implement it with two cheaper instructions, e.g. 11295/// LEA + SHL, LEA + LEA. 11296static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG, 11297 TargetLowering::DAGCombinerInfo &DCI) { 11298 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11299 return SDValue(); 11300 11301 EVT VT = N->getValueType(0); 11302 if (VT != MVT::i64) 11303 return SDValue(); 11304 11305 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11306 if (!C) 11307 return SDValue(); 11308 uint64_t MulAmt = C->getZExtValue(); 11309 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9) 11310 return SDValue(); 11311 11312 uint64_t MulAmt1 = 0; 11313 uint64_t MulAmt2 = 0; 11314 if ((MulAmt % 9) == 0) { 11315 MulAmt1 = 9; 11316 MulAmt2 = MulAmt / 9; 11317 } else if ((MulAmt % 5) == 0) { 11318 MulAmt1 = 5; 11319 MulAmt2 = MulAmt / 5; 11320 } else if ((MulAmt % 3) == 0) { 11321 MulAmt1 = 3; 11322 MulAmt2 = MulAmt / 3; 11323 } 11324 if (MulAmt2 && 11325 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){ 11326 DebugLoc DL = N->getDebugLoc(); 11327 11328 if (isPowerOf2_64(MulAmt2) && 11329 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD)) 11330 // If second multiplifer is pow2, issue it first. We want the multiply by 11331 // 3, 5, or 9 to be folded into the addressing mode unless the lone use 11332 // is an add. 11333 std::swap(MulAmt1, MulAmt2); 11334 11335 SDValue NewMul; 11336 if (isPowerOf2_64(MulAmt1)) 11337 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 11338 DAG.getConstant(Log2_64(MulAmt1), MVT::i8)); 11339 else 11340 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0), 11341 DAG.getConstant(MulAmt1, VT)); 11342 11343 if (isPowerOf2_64(MulAmt2)) 11344 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul, 11345 DAG.getConstant(Log2_64(MulAmt2), MVT::i8)); 11346 else 11347 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul, 11348 DAG.getConstant(MulAmt2, VT)); 11349 11350 // Do not add new nodes to DAG combiner worklist. 11351 DCI.CombineTo(N, NewMul, false); 11352 } 11353 return SDValue(); 11354} 11355 11356static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) { 11357 SDValue N0 = N->getOperand(0); 11358 SDValue N1 = N->getOperand(1); 11359 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 11360 EVT VT = N0.getValueType(); 11361 11362 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2)) 11363 // since the result of setcc_c is all zero's or all ones. 11364 if (N1C && N0.getOpcode() == ISD::AND && 11365 N0.getOperand(1).getOpcode() == ISD::Constant) { 11366 SDValue N00 = N0.getOperand(0); 11367 if (N00.getOpcode() == X86ISD::SETCC_CARRY || 11368 ((N00.getOpcode() == ISD::ANY_EXTEND || 11369 N00.getOpcode() == ISD::ZERO_EXTEND) && 11370 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) { 11371 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 11372 APInt ShAmt = N1C->getAPIntValue(); 11373 Mask = Mask.shl(ShAmt); 11374 if (Mask != 0) 11375 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 11376 N00, DAG.getConstant(Mask, VT)); 11377 } 11378 } 11379 11380 return SDValue(); 11381} 11382 11383/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts 11384/// when possible. 11385static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG, 11386 const X86Subtarget *Subtarget) { 11387 EVT VT = N->getValueType(0); 11388 if (!VT.isVector() && VT.isInteger() && 11389 N->getOpcode() == ISD::SHL) 11390 return PerformSHLCombine(N, DAG); 11391 11392 // On X86 with SSE2 support, we can transform this to a vector shift if 11393 // all elements are shifted by the same amount. We can't do this in legalize 11394 // because the a constant vector is typically transformed to a constant pool 11395 // so we have no knowledge of the shift amount. 11396 if (!Subtarget->hasSSE2()) 11397 return SDValue(); 11398 11399 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16) 11400 return SDValue(); 11401 11402 SDValue ShAmtOp = N->getOperand(1); 11403 EVT EltVT = VT.getVectorElementType(); 11404 DebugLoc DL = N->getDebugLoc(); 11405 SDValue BaseShAmt = SDValue(); 11406 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) { 11407 unsigned NumElts = VT.getVectorNumElements(); 11408 unsigned i = 0; 11409 for (; i != NumElts; ++i) { 11410 SDValue Arg = ShAmtOp.getOperand(i); 11411 if (Arg.getOpcode() == ISD::UNDEF) continue; 11412 BaseShAmt = Arg; 11413 break; 11414 } 11415 for (; i != NumElts; ++i) { 11416 SDValue Arg = ShAmtOp.getOperand(i); 11417 if (Arg.getOpcode() == ISD::UNDEF) continue; 11418 if (Arg != BaseShAmt) { 11419 return SDValue(); 11420 } 11421 } 11422 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE && 11423 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) { 11424 SDValue InVec = ShAmtOp.getOperand(0); 11425 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 11426 unsigned NumElts = InVec.getValueType().getVectorNumElements(); 11427 unsigned i = 0; 11428 for (; i != NumElts; ++i) { 11429 SDValue Arg = InVec.getOperand(i); 11430 if (Arg.getOpcode() == ISD::UNDEF) continue; 11431 BaseShAmt = Arg; 11432 break; 11433 } 11434 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) { 11435 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) { 11436 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex(); 11437 if (C->getZExtValue() == SplatIdx) 11438 BaseShAmt = InVec.getOperand(1); 11439 } 11440 } 11441 if (BaseShAmt.getNode() == 0) 11442 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp, 11443 DAG.getIntPtrConstant(0)); 11444 } else 11445 return SDValue(); 11446 11447 // The shift amount is an i32. 11448 if (EltVT.bitsGT(MVT::i32)) 11449 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt); 11450 else if (EltVT.bitsLT(MVT::i32)) 11451 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt); 11452 11453 // The shift amount is identical so we can do a vector shift. 11454 SDValue ValOp = N->getOperand(0); 11455 switch (N->getOpcode()) { 11456 default: 11457 llvm_unreachable("Unknown shift opcode!"); 11458 break; 11459 case ISD::SHL: 11460 if (VT == MVT::v2i64) 11461 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11462 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 11463 ValOp, BaseShAmt); 11464 if (VT == MVT::v4i32) 11465 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11466 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 11467 ValOp, BaseShAmt); 11468 if (VT == MVT::v8i16) 11469 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11470 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 11471 ValOp, BaseShAmt); 11472 break; 11473 case ISD::SRA: 11474 if (VT == MVT::v4i32) 11475 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11476 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32), 11477 ValOp, BaseShAmt); 11478 if (VT == MVT::v8i16) 11479 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11480 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32), 11481 ValOp, BaseShAmt); 11482 break; 11483 case ISD::SRL: 11484 if (VT == MVT::v2i64) 11485 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11486 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 11487 ValOp, BaseShAmt); 11488 if (VT == MVT::v4i32) 11489 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11490 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32), 11491 ValOp, BaseShAmt); 11492 if (VT == MVT::v8i16) 11493 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11494 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 11495 ValOp, BaseShAmt); 11496 break; 11497 } 11498 return SDValue(); 11499} 11500 11501 11502static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG, 11503 TargetLowering::DAGCombinerInfo &DCI, 11504 const X86Subtarget *Subtarget) { 11505 if (DCI.isBeforeLegalizeOps()) 11506 return SDValue(); 11507 11508 // Want to form PANDN nodes, in the hopes of then easily combining them with 11509 // OR and AND nodes to form PBLEND/PSIGN. 11510 EVT VT = N->getValueType(0); 11511 if (VT != MVT::v2i64) 11512 return SDValue(); 11513 11514 SDValue N0 = N->getOperand(0); 11515 SDValue N1 = N->getOperand(1); 11516 DebugLoc DL = N->getDebugLoc(); 11517 11518 // Check LHS for vnot 11519 if (N0.getOpcode() == ISD::XOR && 11520 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) 11521 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1); 11522 11523 // Check RHS for vnot 11524 if (N1.getOpcode() == ISD::XOR && 11525 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) 11526 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0); 11527 11528 return SDValue(); 11529} 11530 11531static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG, 11532 TargetLowering::DAGCombinerInfo &DCI, 11533 const X86Subtarget *Subtarget) { 11534 if (DCI.isBeforeLegalizeOps()) 11535 return SDValue(); 11536 11537 EVT VT = N->getValueType(0); 11538 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64) 11539 return SDValue(); 11540 11541 SDValue N0 = N->getOperand(0); 11542 SDValue N1 = N->getOperand(1); 11543 11544 // look for psign/blend 11545 if (Subtarget->hasSSSE3()) { 11546 if (VT == MVT::v2i64) { 11547 // Canonicalize pandn to RHS 11548 if (N0.getOpcode() == X86ISD::PANDN) 11549 std::swap(N0, N1); 11550 // or (and (m, x), (pandn m, y)) 11551 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) { 11552 SDValue Mask = N1.getOperand(0); 11553 SDValue X = N1.getOperand(1); 11554 SDValue Y; 11555 if (N0.getOperand(0) == Mask) 11556 Y = N0.getOperand(1); 11557 if (N0.getOperand(1) == Mask) 11558 Y = N0.getOperand(0); 11559 11560 // Check to see if the mask appeared in both the AND and PANDN and 11561 if (!Y.getNode()) 11562 return SDValue(); 11563 11564 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them. 11565 if (Mask.getOpcode() != ISD::BITCAST || 11566 X.getOpcode() != ISD::BITCAST || 11567 Y.getOpcode() != ISD::BITCAST) 11568 return SDValue(); 11569 11570 // Look through mask bitcast. 11571 Mask = Mask.getOperand(0); 11572 EVT MaskVT = Mask.getValueType(); 11573 11574 // Validate that the Mask operand is a vector sra node. The sra node 11575 // will be an intrinsic. 11576 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN) 11577 return SDValue(); 11578 11579 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but 11580 // there is no psrai.b 11581 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) { 11582 case Intrinsic::x86_sse2_psrai_w: 11583 case Intrinsic::x86_sse2_psrai_d: 11584 break; 11585 default: return SDValue(); 11586 } 11587 11588 // Check that the SRA is all signbits. 11589 SDValue SraC = Mask.getOperand(2); 11590 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue(); 11591 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits(); 11592 if ((SraAmt + 1) != EltBits) 11593 return SDValue(); 11594 11595 DebugLoc DL = N->getDebugLoc(); 11596 11597 // Now we know we at least have a plendvb with the mask val. See if 11598 // we can form a psignb/w/d. 11599 // psign = x.type == y.type == mask.type && y = sub(0, x); 11600 X = X.getOperand(0); 11601 Y = Y.getOperand(0); 11602 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X && 11603 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) && 11604 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){ 11605 unsigned Opc = 0; 11606 switch (EltBits) { 11607 case 8: Opc = X86ISD::PSIGNB; break; 11608 case 16: Opc = X86ISD::PSIGNW; break; 11609 case 32: Opc = X86ISD::PSIGND; break; 11610 default: break; 11611 } 11612 if (Opc) { 11613 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1)); 11614 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign); 11615 } 11616 } 11617 // PBLENDVB only available on SSE 4.1 11618 if (!Subtarget->hasSSE41()) 11619 return SDValue(); 11620 11621 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X); 11622 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y); 11623 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask); 11624 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask); 11625 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask); 11626 } 11627 } 11628 } 11629 11630 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c) 11631 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 11632 std::swap(N0, N1); 11633 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 11634 return SDValue(); 11635 if (!N0.hasOneUse() || !N1.hasOneUse()) 11636 return SDValue(); 11637 11638 SDValue ShAmt0 = N0.getOperand(1); 11639 if (ShAmt0.getValueType() != MVT::i8) 11640 return SDValue(); 11641 SDValue ShAmt1 = N1.getOperand(1); 11642 if (ShAmt1.getValueType() != MVT::i8) 11643 return SDValue(); 11644 if (ShAmt0.getOpcode() == ISD::TRUNCATE) 11645 ShAmt0 = ShAmt0.getOperand(0); 11646 if (ShAmt1.getOpcode() == ISD::TRUNCATE) 11647 ShAmt1 = ShAmt1.getOperand(0); 11648 11649 DebugLoc DL = N->getDebugLoc(); 11650 unsigned Opc = X86ISD::SHLD; 11651 SDValue Op0 = N0.getOperand(0); 11652 SDValue Op1 = N1.getOperand(0); 11653 if (ShAmt0.getOpcode() == ISD::SUB) { 11654 Opc = X86ISD::SHRD; 11655 std::swap(Op0, Op1); 11656 std::swap(ShAmt0, ShAmt1); 11657 } 11658 11659 unsigned Bits = VT.getSizeInBits(); 11660 if (ShAmt1.getOpcode() == ISD::SUB) { 11661 SDValue Sum = ShAmt1.getOperand(0); 11662 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) { 11663 SDValue ShAmt1Op1 = ShAmt1.getOperand(1); 11664 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE) 11665 ShAmt1Op1 = ShAmt1Op1.getOperand(0); 11666 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0) 11667 return DAG.getNode(Opc, DL, VT, 11668 Op0, Op1, 11669 DAG.getNode(ISD::TRUNCATE, DL, 11670 MVT::i8, ShAmt0)); 11671 } 11672 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) { 11673 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0); 11674 if (ShAmt0C && 11675 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits) 11676 return DAG.getNode(Opc, DL, VT, 11677 N0.getOperand(0), N1.getOperand(0), 11678 DAG.getNode(ISD::TRUNCATE, DL, 11679 MVT::i8, ShAmt0)); 11680 } 11681 11682 return SDValue(); 11683} 11684 11685/// PerformSTORECombine - Do target-specific dag combines on STORE nodes. 11686static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG, 11687 const X86Subtarget *Subtarget) { 11688 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering 11689 // the FP state in cases where an emms may be missing. 11690 // A preferable solution to the general problem is to figure out the right 11691 // places to insert EMMS. This qualifies as a quick hack. 11692 11693 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode. 11694 StoreSDNode *St = cast<StoreSDNode>(N); 11695 EVT VT = St->getValue().getValueType(); 11696 if (VT.getSizeInBits() != 64) 11697 return SDValue(); 11698 11699 const Function *F = DAG.getMachineFunction().getFunction(); 11700 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat); 11701 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps 11702 && Subtarget->hasSSE2(); 11703 if ((VT.isVector() || 11704 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) && 11705 isa<LoadSDNode>(St->getValue()) && 11706 !cast<LoadSDNode>(St->getValue())->isVolatile() && 11707 St->getChain().hasOneUse() && !St->isVolatile()) { 11708 SDNode* LdVal = St->getValue().getNode(); 11709 LoadSDNode *Ld = 0; 11710 int TokenFactorIndex = -1; 11711 SmallVector<SDValue, 8> Ops; 11712 SDNode* ChainVal = St->getChain().getNode(); 11713 // Must be a store of a load. We currently handle two cases: the load 11714 // is a direct child, and it's under an intervening TokenFactor. It is 11715 // possible to dig deeper under nested TokenFactors. 11716 if (ChainVal == LdVal) 11717 Ld = cast<LoadSDNode>(St->getChain()); 11718 else if (St->getValue().hasOneUse() && 11719 ChainVal->getOpcode() == ISD::TokenFactor) { 11720 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) { 11721 if (ChainVal->getOperand(i).getNode() == LdVal) { 11722 TokenFactorIndex = i; 11723 Ld = cast<LoadSDNode>(St->getValue()); 11724 } else 11725 Ops.push_back(ChainVal->getOperand(i)); 11726 } 11727 } 11728 11729 if (!Ld || !ISD::isNormalLoad(Ld)) 11730 return SDValue(); 11731 11732 // If this is not the MMX case, i.e. we are just turning i64 load/store 11733 // into f64 load/store, avoid the transformation if there are multiple 11734 // uses of the loaded value. 11735 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0)) 11736 return SDValue(); 11737 11738 DebugLoc LdDL = Ld->getDebugLoc(); 11739 DebugLoc StDL = N->getDebugLoc(); 11740 // If we are a 64-bit capable x86, lower to a single movq load/store pair. 11741 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store 11742 // pair instead. 11743 if (Subtarget->is64Bit() || F64IsLegal) { 11744 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64; 11745 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(), 11746 Ld->getPointerInfo(), Ld->isVolatile(), 11747 Ld->isNonTemporal(), Ld->getAlignment()); 11748 SDValue NewChain = NewLd.getValue(1); 11749 if (TokenFactorIndex != -1) { 11750 Ops.push_back(NewChain); 11751 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 11752 Ops.size()); 11753 } 11754 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(), 11755 St->getPointerInfo(), 11756 St->isVolatile(), St->isNonTemporal(), 11757 St->getAlignment()); 11758 } 11759 11760 // Otherwise, lower to two pairs of 32-bit loads / stores. 11761 SDValue LoAddr = Ld->getBasePtr(); 11762 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr, 11763 DAG.getConstant(4, MVT::i32)); 11764 11765 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr, 11766 Ld->getPointerInfo(), 11767 Ld->isVolatile(), Ld->isNonTemporal(), 11768 Ld->getAlignment()); 11769 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr, 11770 Ld->getPointerInfo().getWithOffset(4), 11771 Ld->isVolatile(), Ld->isNonTemporal(), 11772 MinAlign(Ld->getAlignment(), 4)); 11773 11774 SDValue NewChain = LoLd.getValue(1); 11775 if (TokenFactorIndex != -1) { 11776 Ops.push_back(LoLd); 11777 Ops.push_back(HiLd); 11778 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 11779 Ops.size()); 11780 } 11781 11782 LoAddr = St->getBasePtr(); 11783 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr, 11784 DAG.getConstant(4, MVT::i32)); 11785 11786 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr, 11787 St->getPointerInfo(), 11788 St->isVolatile(), St->isNonTemporal(), 11789 St->getAlignment()); 11790 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr, 11791 St->getPointerInfo().getWithOffset(4), 11792 St->isVolatile(), 11793 St->isNonTemporal(), 11794 MinAlign(St->getAlignment(), 4)); 11795 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt); 11796 } 11797 return SDValue(); 11798} 11799 11800/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and 11801/// X86ISD::FXOR nodes. 11802static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) { 11803 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR); 11804 // F[X]OR(0.0, x) -> x 11805 // F[X]OR(x, 0.0) -> x 11806 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 11807 if (C->getValueAPF().isPosZero()) 11808 return N->getOperand(1); 11809 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 11810 if (C->getValueAPF().isPosZero()) 11811 return N->getOperand(0); 11812 return SDValue(); 11813} 11814 11815/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes. 11816static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) { 11817 // FAND(0.0, x) -> 0.0 11818 // FAND(x, 0.0) -> 0.0 11819 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 11820 if (C->getValueAPF().isPosZero()) 11821 return N->getOperand(0); 11822 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 11823 if (C->getValueAPF().isPosZero()) 11824 return N->getOperand(1); 11825 return SDValue(); 11826} 11827 11828static SDValue PerformBTCombine(SDNode *N, 11829 SelectionDAG &DAG, 11830 TargetLowering::DAGCombinerInfo &DCI) { 11831 // BT ignores high bits in the bit index operand. 11832 SDValue Op1 = N->getOperand(1); 11833 if (Op1.hasOneUse()) { 11834 unsigned BitWidth = Op1.getValueSizeInBits(); 11835 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth)); 11836 APInt KnownZero, KnownOne; 11837 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 11838 !DCI.isBeforeLegalizeOps()); 11839 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11840 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) || 11841 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO)) 11842 DCI.CommitTargetLoweringOpt(TLO); 11843 } 11844 return SDValue(); 11845} 11846 11847static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) { 11848 SDValue Op = N->getOperand(0); 11849 if (Op.getOpcode() == ISD::BITCAST) 11850 Op = Op.getOperand(0); 11851 EVT VT = N->getValueType(0), OpVT = Op.getValueType(); 11852 if (Op.getOpcode() == X86ISD::VZEXT_LOAD && 11853 VT.getVectorElementType().getSizeInBits() == 11854 OpVT.getVectorElementType().getSizeInBits()) { 11855 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op); 11856 } 11857 return SDValue(); 11858} 11859 11860static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) { 11861 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) -> 11862 // (and (i32 x86isd::setcc_carry), 1) 11863 // This eliminates the zext. This transformation is necessary because 11864 // ISD::SETCC is always legalized to i8. 11865 DebugLoc dl = N->getDebugLoc(); 11866 SDValue N0 = N->getOperand(0); 11867 EVT VT = N->getValueType(0); 11868 if (N0.getOpcode() == ISD::AND && 11869 N0.hasOneUse() && 11870 N0.getOperand(0).hasOneUse()) { 11871 SDValue N00 = N0.getOperand(0); 11872 if (N00.getOpcode() != X86ISD::SETCC_CARRY) 11873 return SDValue(); 11874 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 11875 if (!C || C->getZExtValue() != 1) 11876 return SDValue(); 11877 return DAG.getNode(ISD::AND, dl, VT, 11878 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, 11879 N00.getOperand(0), N00.getOperand(1)), 11880 DAG.getConstant(1, VT)); 11881 } 11882 11883 return SDValue(); 11884} 11885 11886// Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT 11887static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) { 11888 unsigned X86CC = N->getConstantOperandVal(0); 11889 SDValue EFLAG = N->getOperand(1); 11890 DebugLoc DL = N->getDebugLoc(); 11891 11892 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without 11893 // a zext and produces an all-ones bit which is more useful than 0/1 in some 11894 // cases. 11895 if (X86CC == X86::COND_B) 11896 return DAG.getNode(ISD::AND, DL, MVT::i8, 11897 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8, 11898 DAG.getConstant(X86CC, MVT::i8), EFLAG), 11899 DAG.getConstant(1, MVT::i8)); 11900 11901 return SDValue(); 11902} 11903 11904// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS 11905static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG, 11906 X86TargetLowering::DAGCombinerInfo &DCI) { 11907 // If the LHS and RHS of the ADC node are zero, then it can't overflow and 11908 // the result is either zero or one (depending on the input carry bit). 11909 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1. 11910 if (X86::isZeroNode(N->getOperand(0)) && 11911 X86::isZeroNode(N->getOperand(1)) && 11912 // We don't have a good way to replace an EFLAGS use, so only do this when 11913 // dead right now. 11914 SDValue(N, 1).use_empty()) { 11915 DebugLoc DL = N->getDebugLoc(); 11916 EVT VT = N->getValueType(0); 11917 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1)); 11918 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT, 11919 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, 11920 DAG.getConstant(X86::COND_B,MVT::i8), 11921 N->getOperand(2)), 11922 DAG.getConstant(1, VT)); 11923 return DCI.CombineTo(N, Res1, CarryOut); 11924 } 11925 11926 return SDValue(); 11927} 11928 11929// fold (add Y, (sete X, 0)) -> adc 0, Y 11930// (add Y, (setne X, 0)) -> sbb -1, Y 11931// (sub (sete X, 0), Y) -> sbb 0, Y 11932// (sub (setne X, 0), Y) -> adc -1, Y 11933static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) { 11934 DebugLoc DL = N->getDebugLoc(); 11935 11936 // Look through ZExts. 11937 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0); 11938 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse()) 11939 return SDValue(); 11940 11941 SDValue SetCC = Ext.getOperand(0); 11942 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse()) 11943 return SDValue(); 11944 11945 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0); 11946 if (CC != X86::COND_E && CC != X86::COND_NE) 11947 return SDValue(); 11948 11949 SDValue Cmp = SetCC.getOperand(1); 11950 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() || 11951 !X86::isZeroNode(Cmp.getOperand(1)) || 11952 !Cmp.getOperand(0).getValueType().isInteger()) 11953 return SDValue(); 11954 11955 SDValue CmpOp0 = Cmp.getOperand(0); 11956 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0, 11957 DAG.getConstant(1, CmpOp0.getValueType())); 11958 11959 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1); 11960 if (CC == X86::COND_NE) 11961 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB, 11962 DL, OtherVal.getValueType(), OtherVal, 11963 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp); 11964 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC, 11965 DL, OtherVal.getValueType(), OtherVal, 11966 DAG.getConstant(0, OtherVal.getValueType()), NewCmp); 11967} 11968 11969SDValue X86TargetLowering::PerformDAGCombine(SDNode *N, 11970 DAGCombinerInfo &DCI) const { 11971 SelectionDAG &DAG = DCI.DAG; 11972 switch (N->getOpcode()) { 11973 default: break; 11974 case ISD::EXTRACT_VECTOR_ELT: 11975 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this); 11976 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget); 11977 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI); 11978 case ISD::ADD: 11979 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG); 11980 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI); 11981 case ISD::MUL: return PerformMulCombine(N, DAG, DCI); 11982 case ISD::SHL: 11983 case ISD::SRA: 11984 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget); 11985 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget); 11986 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget); 11987 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget); 11988 case X86ISD::FXOR: 11989 case X86ISD::FOR: return PerformFORCombine(N, DAG); 11990 case X86ISD::FAND: return PerformFANDCombine(N, DAG); 11991 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI); 11992 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG); 11993 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG); 11994 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG); 11995 case X86ISD::SHUFPS: // Handle all target specific shuffles 11996 case X86ISD::SHUFPD: 11997 case X86ISD::PALIGN: 11998 case X86ISD::PUNPCKHBW: 11999 case X86ISD::PUNPCKHWD: 12000 case X86ISD::PUNPCKHDQ: 12001 case X86ISD::PUNPCKHQDQ: 12002 case X86ISD::UNPCKHPS: 12003 case X86ISD::UNPCKHPD: 12004 case X86ISD::PUNPCKLBW: 12005 case X86ISD::PUNPCKLWD: 12006 case X86ISD::PUNPCKLDQ: 12007 case X86ISD::PUNPCKLQDQ: 12008 case X86ISD::UNPCKLPS: 12009 case X86ISD::UNPCKLPD: 12010 case X86ISD::VUNPCKLPS: 12011 case X86ISD::VUNPCKLPD: 12012 case X86ISD::VUNPCKLPSY: 12013 case X86ISD::VUNPCKLPDY: 12014 case X86ISD::MOVHLPS: 12015 case X86ISD::MOVLHPS: 12016 case X86ISD::PSHUFD: 12017 case X86ISD::PSHUFHW: 12018 case X86ISD::PSHUFLW: 12019 case X86ISD::MOVSS: 12020 case X86ISD::MOVSD: 12021 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI); 12022 } 12023 12024 return SDValue(); 12025} 12026 12027/// isTypeDesirableForOp - Return true if the target has native support for 12028/// the specified value type and it is 'desirable' to use the type for the 12029/// given node type. e.g. On x86 i16 is legal, but undesirable since i16 12030/// instruction encodings are longer and some i16 instructions are slow. 12031bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const { 12032 if (!isTypeLegal(VT)) 12033 return false; 12034 if (VT != MVT::i16) 12035 return true; 12036 12037 switch (Opc) { 12038 default: 12039 return true; 12040 case ISD::LOAD: 12041 case ISD::SIGN_EXTEND: 12042 case ISD::ZERO_EXTEND: 12043 case ISD::ANY_EXTEND: 12044 case ISD::SHL: 12045 case ISD::SRL: 12046 case ISD::SUB: 12047 case ISD::ADD: 12048 case ISD::MUL: 12049 case ISD::AND: 12050 case ISD::OR: 12051 case ISD::XOR: 12052 return false; 12053 } 12054} 12055 12056/// IsDesirableToPromoteOp - This method query the target whether it is 12057/// beneficial for dag combiner to promote the specified node. If true, it 12058/// should return the desired promotion type by reference. 12059bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 12060 EVT VT = Op.getValueType(); 12061 if (VT != MVT::i16) 12062 return false; 12063 12064 bool Promote = false; 12065 bool Commute = false; 12066 switch (Op.getOpcode()) { 12067 default: break; 12068 case ISD::LOAD: { 12069 LoadSDNode *LD = cast<LoadSDNode>(Op); 12070 // If the non-extending load has a single use and it's not live out, then it 12071 // might be folded. 12072 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&& 12073 Op.hasOneUse()*/) { 12074 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 12075 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 12076 // The only case where we'd want to promote LOAD (rather then it being 12077 // promoted as an operand is when it's only use is liveout. 12078 if (UI->getOpcode() != ISD::CopyToReg) 12079 return false; 12080 } 12081 } 12082 Promote = true; 12083 break; 12084 } 12085 case ISD::SIGN_EXTEND: 12086 case ISD::ZERO_EXTEND: 12087 case ISD::ANY_EXTEND: 12088 Promote = true; 12089 break; 12090 case ISD::SHL: 12091 case ISD::SRL: { 12092 SDValue N0 = Op.getOperand(0); 12093 // Look out for (store (shl (load), x)). 12094 if (MayFoldLoad(N0) && MayFoldIntoStore(Op)) 12095 return false; 12096 Promote = true; 12097 break; 12098 } 12099 case ISD::ADD: 12100 case ISD::MUL: 12101 case ISD::AND: 12102 case ISD::OR: 12103 case ISD::XOR: 12104 Commute = true; 12105 // fallthrough 12106 case ISD::SUB: { 12107 SDValue N0 = Op.getOperand(0); 12108 SDValue N1 = Op.getOperand(1); 12109 if (!Commute && MayFoldLoad(N1)) 12110 return false; 12111 // Avoid disabling potential load folding opportunities. 12112 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op))) 12113 return false; 12114 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op))) 12115 return false; 12116 Promote = true; 12117 } 12118 } 12119 12120 PVT = MVT::i32; 12121 return Promote; 12122} 12123 12124//===----------------------------------------------------------------------===// 12125// X86 Inline Assembly Support 12126//===----------------------------------------------------------------------===// 12127 12128bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const { 12129 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 12130 12131 std::string AsmStr = IA->getAsmString(); 12132 12133 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a" 12134 SmallVector<StringRef, 4> AsmPieces; 12135 SplitString(AsmStr, AsmPieces, ";\n"); 12136 12137 switch (AsmPieces.size()) { 12138 default: return false; 12139 case 1: 12140 AsmStr = AsmPieces[0]; 12141 AsmPieces.clear(); 12142 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace. 12143 12144 // FIXME: this should verify that we are targetting a 486 or better. If not, 12145 // we will turn this bswap into something that will be lowered to logical ops 12146 // instead of emitting the bswap asm. For now, we don't support 486 or lower 12147 // so don't worry about this. 12148 // bswap $0 12149 if (AsmPieces.size() == 2 && 12150 (AsmPieces[0] == "bswap" || 12151 AsmPieces[0] == "bswapq" || 12152 AsmPieces[0] == "bswapl") && 12153 (AsmPieces[1] == "$0" || 12154 AsmPieces[1] == "${0:q}")) { 12155 // No need to check constraints, nothing other than the equivalent of 12156 // "=r,0" would be valid here. 12157 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12158 if (!Ty || Ty->getBitWidth() % 16 != 0) 12159 return false; 12160 return IntrinsicLowering::LowerToByteSwap(CI); 12161 } 12162 // rorw $$8, ${0:w} --> llvm.bswap.i16 12163 if (CI->getType()->isIntegerTy(16) && 12164 AsmPieces.size() == 3 && 12165 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") && 12166 AsmPieces[1] == "$$8," && 12167 AsmPieces[2] == "${0:w}" && 12168 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 12169 AsmPieces.clear(); 12170 const std::string &ConstraintsStr = IA->getConstraintString(); 12171 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 12172 std::sort(AsmPieces.begin(), AsmPieces.end()); 12173 if (AsmPieces.size() == 4 && 12174 AsmPieces[0] == "~{cc}" && 12175 AsmPieces[1] == "~{dirflag}" && 12176 AsmPieces[2] == "~{flags}" && 12177 AsmPieces[3] == "~{fpsr}") { 12178 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12179 if (!Ty || Ty->getBitWidth() % 16 != 0) 12180 return false; 12181 return IntrinsicLowering::LowerToByteSwap(CI); 12182 } 12183 } 12184 break; 12185 case 3: 12186 if (CI->getType()->isIntegerTy(32) && 12187 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 12188 SmallVector<StringRef, 4> Words; 12189 SplitString(AsmPieces[0], Words, " \t,"); 12190 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 12191 Words[2] == "${0:w}") { 12192 Words.clear(); 12193 SplitString(AsmPieces[1], Words, " \t,"); 12194 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" && 12195 Words[2] == "$0") { 12196 Words.clear(); 12197 SplitString(AsmPieces[2], Words, " \t,"); 12198 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 12199 Words[2] == "${0:w}") { 12200 AsmPieces.clear(); 12201 const std::string &ConstraintsStr = IA->getConstraintString(); 12202 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 12203 std::sort(AsmPieces.begin(), AsmPieces.end()); 12204 if (AsmPieces.size() == 4 && 12205 AsmPieces[0] == "~{cc}" && 12206 AsmPieces[1] == "~{dirflag}" && 12207 AsmPieces[2] == "~{flags}" && 12208 AsmPieces[3] == "~{fpsr}") { 12209 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12210 if (!Ty || Ty->getBitWidth() % 16 != 0) 12211 return false; 12212 return IntrinsicLowering::LowerToByteSwap(CI); 12213 } 12214 } 12215 } 12216 } 12217 } 12218 12219 if (CI->getType()->isIntegerTy(64)) { 12220 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 12221 if (Constraints.size() >= 2 && 12222 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" && 12223 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") { 12224 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64 12225 SmallVector<StringRef, 4> Words; 12226 SplitString(AsmPieces[0], Words, " \t"); 12227 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") { 12228 Words.clear(); 12229 SplitString(AsmPieces[1], Words, " \t"); 12230 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") { 12231 Words.clear(); 12232 SplitString(AsmPieces[2], Words, " \t,"); 12233 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" && 12234 Words[2] == "%edx") { 12235 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12236 if (!Ty || Ty->getBitWidth() % 16 != 0) 12237 return false; 12238 return IntrinsicLowering::LowerToByteSwap(CI); 12239 } 12240 } 12241 } 12242 } 12243 } 12244 break; 12245 } 12246 return false; 12247} 12248 12249 12250 12251/// getConstraintType - Given a constraint letter, return the type of 12252/// constraint it is for this target. 12253X86TargetLowering::ConstraintType 12254X86TargetLowering::getConstraintType(const std::string &Constraint) const { 12255 if (Constraint.size() == 1) { 12256 switch (Constraint[0]) { 12257 case 'R': 12258 case 'q': 12259 case 'Q': 12260 case 'f': 12261 case 't': 12262 case 'u': 12263 case 'y': 12264 case 'x': 12265 case 'Y': 12266 return C_RegisterClass; 12267 case 'a': 12268 case 'b': 12269 case 'c': 12270 case 'd': 12271 case 'S': 12272 case 'D': 12273 case 'A': 12274 return C_Register; 12275 case 'I': 12276 case 'J': 12277 case 'K': 12278 case 'L': 12279 case 'M': 12280 case 'N': 12281 case 'G': 12282 case 'C': 12283 case 'e': 12284 case 'Z': 12285 return C_Other; 12286 default: 12287 break; 12288 } 12289 } 12290 return TargetLowering::getConstraintType(Constraint); 12291} 12292 12293/// Examine constraint type and operand type and determine a weight value. 12294/// This object must already have been set up with the operand type 12295/// and the current alternative constraint selected. 12296TargetLowering::ConstraintWeight 12297 X86TargetLowering::getSingleConstraintMatchWeight( 12298 AsmOperandInfo &info, const char *constraint) const { 12299 ConstraintWeight weight = CW_Invalid; 12300 Value *CallOperandVal = info.CallOperandVal; 12301 // If we don't have a value, we can't do a match, 12302 // but allow it at the lowest weight. 12303 if (CallOperandVal == NULL) 12304 return CW_Default; 12305 const Type *type = CallOperandVal->getType(); 12306 // Look at the constraint type. 12307 switch (*constraint) { 12308 default: 12309 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12310 case 'R': 12311 case 'q': 12312 case 'Q': 12313 case 'a': 12314 case 'b': 12315 case 'c': 12316 case 'd': 12317 case 'S': 12318 case 'D': 12319 case 'A': 12320 if (CallOperandVal->getType()->isIntegerTy()) 12321 weight = CW_SpecificReg; 12322 break; 12323 case 'f': 12324 case 't': 12325 case 'u': 12326 if (type->isFloatingPointTy()) 12327 weight = CW_SpecificReg; 12328 break; 12329 case 'y': 12330 if (type->isX86_MMXTy() && Subtarget->hasMMX()) 12331 weight = CW_SpecificReg; 12332 break; 12333 case 'x': 12334 case 'Y': 12335 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM()) 12336 weight = CW_Register; 12337 break; 12338 case 'I': 12339 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) { 12340 if (C->getZExtValue() <= 31) 12341 weight = CW_Constant; 12342 } 12343 break; 12344 case 'J': 12345 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12346 if (C->getZExtValue() <= 63) 12347 weight = CW_Constant; 12348 } 12349 break; 12350 case 'K': 12351 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12352 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f)) 12353 weight = CW_Constant; 12354 } 12355 break; 12356 case 'L': 12357 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12358 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff)) 12359 weight = CW_Constant; 12360 } 12361 break; 12362 case 'M': 12363 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12364 if (C->getZExtValue() <= 3) 12365 weight = CW_Constant; 12366 } 12367 break; 12368 case 'N': 12369 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12370 if (C->getZExtValue() <= 0xff) 12371 weight = CW_Constant; 12372 } 12373 break; 12374 case 'G': 12375 case 'C': 12376 if (dyn_cast<ConstantFP>(CallOperandVal)) { 12377 weight = CW_Constant; 12378 } 12379 break; 12380 case 'e': 12381 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12382 if ((C->getSExtValue() >= -0x80000000LL) && 12383 (C->getSExtValue() <= 0x7fffffffLL)) 12384 weight = CW_Constant; 12385 } 12386 break; 12387 case 'Z': 12388 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12389 if (C->getZExtValue() <= 0xffffffff) 12390 weight = CW_Constant; 12391 } 12392 break; 12393 } 12394 return weight; 12395} 12396 12397/// LowerXConstraint - try to replace an X constraint, which matches anything, 12398/// with another that has more specific requirements based on the type of the 12399/// corresponding operand. 12400const char *X86TargetLowering:: 12401LowerXConstraint(EVT ConstraintVT) const { 12402 // FP X constraints get lowered to SSE1/2 registers if available, otherwise 12403 // 'f' like normal targets. 12404 if (ConstraintVT.isFloatingPoint()) { 12405 if (Subtarget->hasXMMInt()) 12406 return "Y"; 12407 if (Subtarget->hasXMM()) 12408 return "x"; 12409 } 12410 12411 return TargetLowering::LowerXConstraint(ConstraintVT); 12412} 12413 12414/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12415/// vector. If it is invalid, don't add anything to Ops. 12416void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12417 char Constraint, 12418 std::vector<SDValue>&Ops, 12419 SelectionDAG &DAG) const { 12420 SDValue Result(0, 0); 12421 12422 switch (Constraint) { 12423 default: break; 12424 case 'I': 12425 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12426 if (C->getZExtValue() <= 31) { 12427 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12428 break; 12429 } 12430 } 12431 return; 12432 case 'J': 12433 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12434 if (C->getZExtValue() <= 63) { 12435 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12436 break; 12437 } 12438 } 12439 return; 12440 case 'K': 12441 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12442 if ((int8_t)C->getSExtValue() == C->getSExtValue()) { 12443 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12444 break; 12445 } 12446 } 12447 return; 12448 case 'N': 12449 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12450 if (C->getZExtValue() <= 255) { 12451 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12452 break; 12453 } 12454 } 12455 return; 12456 case 'e': { 12457 // 32-bit signed value 12458 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12459 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 12460 C->getSExtValue())) { 12461 // Widen to 64 bits here to get it sign extended. 12462 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64); 12463 break; 12464 } 12465 // FIXME gcc accepts some relocatable values here too, but only in certain 12466 // memory models; it's complicated. 12467 } 12468 return; 12469 } 12470 case 'Z': { 12471 // 32-bit unsigned value 12472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12473 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 12474 C->getZExtValue())) { 12475 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12476 break; 12477 } 12478 } 12479 // FIXME gcc accepts some relocatable values here too, but only in certain 12480 // memory models; it's complicated. 12481 return; 12482 } 12483 case 'i': { 12484 // Literal immediates are always ok. 12485 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) { 12486 // Widen to 64 bits here to get it sign extended. 12487 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64); 12488 break; 12489 } 12490 12491 // In any sort of PIC mode addresses need to be computed at runtime by 12492 // adding in a register or some sort of table lookup. These can't 12493 // be used as immediates. 12494 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC()) 12495 return; 12496 12497 // If we are in non-pic codegen mode, we allow the address of a global (with 12498 // an optional displacement) to be used with 'i'. 12499 GlobalAddressSDNode *GA = 0; 12500 int64_t Offset = 0; 12501 12502 // Match either (GA), (GA+C), (GA+C1+C2), etc. 12503 while (1) { 12504 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) { 12505 Offset += GA->getOffset(); 12506 break; 12507 } else if (Op.getOpcode() == ISD::ADD) { 12508 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 12509 Offset += C->getZExtValue(); 12510 Op = Op.getOperand(0); 12511 continue; 12512 } 12513 } else if (Op.getOpcode() == ISD::SUB) { 12514 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 12515 Offset += -C->getZExtValue(); 12516 Op = Op.getOperand(0); 12517 continue; 12518 } 12519 } 12520 12521 // Otherwise, this isn't something we can handle, reject it. 12522 return; 12523 } 12524 12525 const GlobalValue *GV = GA->getGlobal(); 12526 // If we require an extra load to get this address, as in PIC mode, we 12527 // can't accept it. 12528 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV, 12529 getTargetMachine()))) 12530 return; 12531 12532 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), 12533 GA->getValueType(0), Offset); 12534 break; 12535 } 12536 } 12537 12538 if (Result.getNode()) { 12539 Ops.push_back(Result); 12540 return; 12541 } 12542 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12543} 12544 12545std::vector<unsigned> X86TargetLowering:: 12546getRegClassForInlineAsmConstraint(const std::string &Constraint, 12547 EVT VT) const { 12548 if (Constraint.size() == 1) { 12549 // FIXME: not handling fp-stack yet! 12550 switch (Constraint[0]) { // GCC X86 Constraint Letters 12551 default: break; // Unknown constraint letter 12552 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode. 12553 if (Subtarget->is64Bit()) { 12554 if (VT == MVT::i32) 12555 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 12556 X86::ESI, X86::EDI, X86::R8D, X86::R9D, 12557 X86::R10D,X86::R11D,X86::R12D, 12558 X86::R13D,X86::R14D,X86::R15D, 12559 X86::EBP, X86::ESP, 0); 12560 else if (VT == MVT::i16) 12561 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 12562 X86::SI, X86::DI, X86::R8W,X86::R9W, 12563 X86::R10W,X86::R11W,X86::R12W, 12564 X86::R13W,X86::R14W,X86::R15W, 12565 X86::BP, X86::SP, 0); 12566 else if (VT == MVT::i8) 12567 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 12568 X86::SIL, X86::DIL, X86::R8B,X86::R9B, 12569 X86::R10B,X86::R11B,X86::R12B, 12570 X86::R13B,X86::R14B,X86::R15B, 12571 X86::BPL, X86::SPL, 0); 12572 12573 else if (VT == MVT::i64) 12574 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 12575 X86::RSI, X86::RDI, X86::R8, X86::R9, 12576 X86::R10, X86::R11, X86::R12, 12577 X86::R13, X86::R14, X86::R15, 12578 X86::RBP, X86::RSP, 0); 12579 12580 break; 12581 } 12582 // 32-bit fallthrough 12583 case 'Q': // Q_REGS 12584 if (VT == MVT::i32) 12585 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0); 12586 else if (VT == MVT::i16) 12587 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0); 12588 else if (VT == MVT::i8) 12589 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0); 12590 else if (VT == MVT::i64) 12591 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0); 12592 break; 12593 } 12594 } 12595 12596 return std::vector<unsigned>(); 12597} 12598 12599std::pair<unsigned, const TargetRegisterClass*> 12600X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 12601 EVT VT) const { 12602 // First, see if this is a constraint that directly corresponds to an LLVM 12603 // register class. 12604 if (Constraint.size() == 1) { 12605 // GCC Constraint Letters 12606 switch (Constraint[0]) { 12607 default: break; 12608 case 'r': // GENERAL_REGS 12609 case 'l': // INDEX_REGS 12610 if (VT == MVT::i8) 12611 return std::make_pair(0U, X86::GR8RegisterClass); 12612 if (VT == MVT::i16) 12613 return std::make_pair(0U, X86::GR16RegisterClass); 12614 if (VT == MVT::i32 || !Subtarget->is64Bit()) 12615 return std::make_pair(0U, X86::GR32RegisterClass); 12616 return std::make_pair(0U, X86::GR64RegisterClass); 12617 case 'R': // LEGACY_REGS 12618 if (VT == MVT::i8) 12619 return std::make_pair(0U, X86::GR8_NOREXRegisterClass); 12620 if (VT == MVT::i16) 12621 return std::make_pair(0U, X86::GR16_NOREXRegisterClass); 12622 if (VT == MVT::i32 || !Subtarget->is64Bit()) 12623 return std::make_pair(0U, X86::GR32_NOREXRegisterClass); 12624 return std::make_pair(0U, X86::GR64_NOREXRegisterClass); 12625 case 'f': // FP Stack registers. 12626 // If SSE is enabled for this VT, use f80 to ensure the isel moves the 12627 // value to the correct fpstack register class. 12628 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT)) 12629 return std::make_pair(0U, X86::RFP32RegisterClass); 12630 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT)) 12631 return std::make_pair(0U, X86::RFP64RegisterClass); 12632 return std::make_pair(0U, X86::RFP80RegisterClass); 12633 case 'y': // MMX_REGS if MMX allowed. 12634 if (!Subtarget->hasMMX()) break; 12635 return std::make_pair(0U, X86::VR64RegisterClass); 12636 case 'Y': // SSE_REGS if SSE2 allowed 12637 if (!Subtarget->hasXMMInt()) break; 12638 // FALL THROUGH. 12639 case 'x': // SSE_REGS if SSE1 allowed 12640 if (!Subtarget->hasXMM()) break; 12641 12642 switch (VT.getSimpleVT().SimpleTy) { 12643 default: break; 12644 // Scalar SSE types. 12645 case MVT::f32: 12646 case MVT::i32: 12647 return std::make_pair(0U, X86::FR32RegisterClass); 12648 case MVT::f64: 12649 case MVT::i64: 12650 return std::make_pair(0U, X86::FR64RegisterClass); 12651 // Vector types. 12652 case MVT::v16i8: 12653 case MVT::v8i16: 12654 case MVT::v4i32: 12655 case MVT::v2i64: 12656 case MVT::v4f32: 12657 case MVT::v2f64: 12658 return std::make_pair(0U, X86::VR128RegisterClass); 12659 } 12660 break; 12661 } 12662 } 12663 12664 // Use the default implementation in TargetLowering to convert the register 12665 // constraint into a member of a register class. 12666 std::pair<unsigned, const TargetRegisterClass*> Res; 12667 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 12668 12669 // Not found as a standard register? 12670 if (Res.second == 0) { 12671 // Map st(0) -> st(7) -> ST0 12672 if (Constraint.size() == 7 && Constraint[0] == '{' && 12673 tolower(Constraint[1]) == 's' && 12674 tolower(Constraint[2]) == 't' && 12675 Constraint[3] == '(' && 12676 (Constraint[4] >= '0' && Constraint[4] <= '7') && 12677 Constraint[5] == ')' && 12678 Constraint[6] == '}') { 12679 12680 Res.first = X86::ST0+Constraint[4]-'0'; 12681 Res.second = X86::RFP80RegisterClass; 12682 return Res; 12683 } 12684 12685 // GCC allows "st(0)" to be called just plain "st". 12686 if (StringRef("{st}").equals_lower(Constraint)) { 12687 Res.first = X86::ST0; 12688 Res.second = X86::RFP80RegisterClass; 12689 return Res; 12690 } 12691 12692 // flags -> EFLAGS 12693 if (StringRef("{flags}").equals_lower(Constraint)) { 12694 Res.first = X86::EFLAGS; 12695 Res.second = X86::CCRRegisterClass; 12696 return Res; 12697 } 12698 12699 // 'A' means EAX + EDX. 12700 if (Constraint == "A") { 12701 Res.first = X86::EAX; 12702 Res.second = X86::GR32_ADRegisterClass; 12703 return Res; 12704 } 12705 return Res; 12706 } 12707 12708 // Otherwise, check to see if this is a register class of the wrong value 12709 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to 12710 // turn into {ax},{dx}. 12711 if (Res.second->hasType(VT)) 12712 return Res; // Correct type already, nothing to do. 12713 12714 // All of the single-register GCC register classes map their values onto 12715 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we 12716 // really want an 8-bit or 32-bit register, map to the appropriate register 12717 // class and return the appropriate register. 12718 if (Res.second == X86::GR16RegisterClass) { 12719 if (VT == MVT::i8) { 12720 unsigned DestReg = 0; 12721 switch (Res.first) { 12722 default: break; 12723 case X86::AX: DestReg = X86::AL; break; 12724 case X86::DX: DestReg = X86::DL; break; 12725 case X86::CX: DestReg = X86::CL; break; 12726 case X86::BX: DestReg = X86::BL; break; 12727 } 12728 if (DestReg) { 12729 Res.first = DestReg; 12730 Res.second = X86::GR8RegisterClass; 12731 } 12732 } else if (VT == MVT::i32) { 12733 unsigned DestReg = 0; 12734 switch (Res.first) { 12735 default: break; 12736 case X86::AX: DestReg = X86::EAX; break; 12737 case X86::DX: DestReg = X86::EDX; break; 12738 case X86::CX: DestReg = X86::ECX; break; 12739 case X86::BX: DestReg = X86::EBX; break; 12740 case X86::SI: DestReg = X86::ESI; break; 12741 case X86::DI: DestReg = X86::EDI; break; 12742 case X86::BP: DestReg = X86::EBP; break; 12743 case X86::SP: DestReg = X86::ESP; break; 12744 } 12745 if (DestReg) { 12746 Res.first = DestReg; 12747 Res.second = X86::GR32RegisterClass; 12748 } 12749 } else if (VT == MVT::i64) { 12750 unsigned DestReg = 0; 12751 switch (Res.first) { 12752 default: break; 12753 case X86::AX: DestReg = X86::RAX; break; 12754 case X86::DX: DestReg = X86::RDX; break; 12755 case X86::CX: DestReg = X86::RCX; break; 12756 case X86::BX: DestReg = X86::RBX; break; 12757 case X86::SI: DestReg = X86::RSI; break; 12758 case X86::DI: DestReg = X86::RDI; break; 12759 case X86::BP: DestReg = X86::RBP; break; 12760 case X86::SP: DestReg = X86::RSP; break; 12761 } 12762 if (DestReg) { 12763 Res.first = DestReg; 12764 Res.second = X86::GR64RegisterClass; 12765 } 12766 } 12767 } else if (Res.second == X86::FR32RegisterClass || 12768 Res.second == X86::FR64RegisterClass || 12769 Res.second == X86::VR128RegisterClass) { 12770 // Handle references to XMM physical registers that got mapped into the 12771 // wrong class. This can happen with constraints like {xmm0} where the 12772 // target independent register mapper will just pick the first match it can 12773 // find, ignoring the required type. 12774 if (VT == MVT::f32) 12775 Res.second = X86::FR32RegisterClass; 12776 else if (VT == MVT::f64) 12777 Res.second = X86::FR64RegisterClass; 12778 else if (X86::VR128RegisterClass->hasType(VT)) 12779 Res.second = X86::VR128RegisterClass; 12780 } 12781 12782 return Res; 12783} 12784