X86ISelLowering.cpp revision ee64be9c176a21a6fd86d2c4eebda571f872d4a2
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/CallSite.h" 49#include "llvm/Support/Debug.h" 50#include "llvm/Support/Dwarf.h" 51#include "llvm/Support/ErrorHandling.h" 52#include "llvm/Support/MathExtras.h" 53#include "llvm/Support/raw_ostream.h" 54#include "llvm/Target/TargetOptions.h" 55using namespace llvm; 56using namespace dwarf; 57 58STATISTIC(NumTailCalls, "Number of tail calls"); 59 60// Forward declarations. 61static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 62 SDValue V2); 63 64static SDValue Insert128BitVector(SDValue Result, 65 SDValue Vec, 66 SDValue Idx, 67 SelectionDAG &DAG, 68 DebugLoc dl); 69 70static SDValue Extract128BitVector(SDValue Vec, 71 SDValue Idx, 72 SelectionDAG &DAG, 73 DebugLoc dl); 74 75/// Generate a DAG to grab 128-bits from a vector > 128 bits. This 76/// sets things up to match to an AVX VEXTRACTF128 instruction or a 77/// simple subregister reference. Idx is an index in the 128 bits we 78/// want. It need not be aligned to a 128-bit bounday. That makes 79/// lowering EXTRACT_VECTOR_ELT operations easier. 80static SDValue Extract128BitVector(SDValue Vec, 81 SDValue Idx, 82 SelectionDAG &DAG, 83 DebugLoc dl) { 84 EVT VT = Vec.getValueType(); 85 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!"); 86 EVT ElVT = VT.getVectorElementType(); 87 int Factor = VT.getSizeInBits()/128; 88 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, 89 VT.getVectorNumElements()/Factor); 90 91 // Extract from UNDEF is UNDEF. 92 if (Vec.getOpcode() == ISD::UNDEF) 93 return DAG.getNode(ISD::UNDEF, dl, ResultVT); 94 95 if (isa<ConstantSDNode>(Idx)) { 96 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 97 98 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR 99 // we can match to VEXTRACTF128. 100 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 101 102 // This is the index of the first element of the 128-bit chunk 103 // we want. 104 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 105 * ElemsPerChunk); 106 107 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 108 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, 109 VecIdx); 110 111 return Result; 112 } 113 114 return SDValue(); 115} 116 117/// Generate a DAG to put 128-bits into a vector > 128 bits. This 118/// sets things up to match to an AVX VINSERTF128 instruction or a 119/// simple superregister reference. Idx is an index in the 128 bits 120/// we want. It need not be aligned to a 128-bit bounday. That makes 121/// lowering INSERT_VECTOR_ELT operations easier. 122static SDValue Insert128BitVector(SDValue Result, 123 SDValue Vec, 124 SDValue Idx, 125 SelectionDAG &DAG, 126 DebugLoc dl) { 127 if (isa<ConstantSDNode>(Idx)) { 128 EVT VT = Vec.getValueType(); 129 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!"); 130 131 EVT ElVT = VT.getVectorElementType(); 132 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 133 EVT ResultVT = Result.getValueType(); 134 135 // Insert the relevant 128 bits. 136 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits(); 137 138 // This is the index of the first element of the 128-bit chunk 139 // we want. 140 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128) 141 * ElemsPerChunk); 142 143 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 144 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, 145 VecIdx); 146 return Result; 147 } 148 149 return SDValue(); 150} 151 152static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) { 153 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); 154 bool is64Bit = Subtarget->is64Bit(); 155 156 if (Subtarget->isTargetEnvMacho()) { 157 if (is64Bit) 158 return new X8664_MachoTargetObjectFile(); 159 return new TargetLoweringObjectFileMachO(); 160 } 161 162 if (Subtarget->isTargetELF()) 163 return new TargetLoweringObjectFileELF(); 164 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 165 return new TargetLoweringObjectFileCOFF(); 166 llvm_unreachable("unknown subtarget type"); 167} 168 169X86TargetLowering::X86TargetLowering(X86TargetMachine &TM) 170 : TargetLowering(TM, createTLOF(TM)) { 171 Subtarget = &TM.getSubtarget<X86Subtarget>(); 172 X86ScalarSSEf64 = Subtarget->hasXMMInt() || Subtarget->hasAVX(); 173 X86ScalarSSEf32 = Subtarget->hasXMM() || Subtarget->hasAVX(); 174 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP; 175 176 RegInfo = TM.getRegisterInfo(); 177 TD = getTargetData(); 178 179 // Set up the TargetLowering object. 180 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }; 181 182 // X86 is weird, it always uses i8 for shift amounts and setcc results. 183 setBooleanContents(ZeroOrOneBooleanContent); 184 // X86-SSE is even stranger. It uses -1 or 0 for vector masks. 185 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 186 187 // For 64-bit since we have so many registers use the ILP scheduler, for 188 // 32-bit code use the register pressure specific scheduling. 189 if (Subtarget->is64Bit()) 190 setSchedulingPreference(Sched::ILP); 191 else 192 setSchedulingPreference(Sched::RegPressure); 193 setStackPointerRegisterToSaveRestore(X86StackPtr); 194 195 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) { 196 // Setup Windows compiler runtime calls. 197 setLibcallName(RTLIB::SDIV_I64, "_alldiv"); 198 setLibcallName(RTLIB::UDIV_I64, "_aulldiv"); 199 setLibcallName(RTLIB::SREM_I64, "_allrem"); 200 setLibcallName(RTLIB::UREM_I64, "_aullrem"); 201 setLibcallName(RTLIB::MUL_I64, "_allmul"); 202 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2"); 203 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2"); 204 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall); 205 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall); 206 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall); 207 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall); 208 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall); 209 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C); 210 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C); 211 } 212 213 if (Subtarget->isTargetDarwin()) { 214 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp. 215 setUseUnderscoreSetJmp(false); 216 setUseUnderscoreLongJmp(false); 217 } else if (Subtarget->isTargetMingw()) { 218 // MS runtime is weird: it exports _setjmp, but longjmp! 219 setUseUnderscoreSetJmp(true); 220 setUseUnderscoreLongJmp(false); 221 } else { 222 setUseUnderscoreSetJmp(true); 223 setUseUnderscoreLongJmp(true); 224 } 225 226 // Set up the register classes. 227 addRegisterClass(MVT::i8, X86::GR8RegisterClass); 228 addRegisterClass(MVT::i16, X86::GR16RegisterClass); 229 addRegisterClass(MVT::i32, X86::GR32RegisterClass); 230 if (Subtarget->is64Bit()) 231 addRegisterClass(MVT::i64, X86::GR64RegisterClass); 232 233 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 234 235 // We don't accept any truncstore of integer registers. 236 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 237 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 238 setTruncStoreAction(MVT::i64, MVT::i8 , Expand); 239 setTruncStoreAction(MVT::i32, MVT::i16, Expand); 240 setTruncStoreAction(MVT::i32, MVT::i8 , Expand); 241 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 242 243 // SETOEQ and SETUNE require checking two conditions. 244 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand); 245 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand); 246 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand); 247 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand); 248 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand); 249 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand); 250 251 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this 252 // operation. 253 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote); 254 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote); 255 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote); 256 257 if (Subtarget->is64Bit()) { 258 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote); 259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand); 260 } else if (!UseSoftFloat) { 261 // We have an algorithm for SSE2->double, and we turn this into a 262 // 64-bit FILD followed by conditional FADD for other targets. 263 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 264 // We have an algorithm for SSE2, and we turn this into a 64-bit 265 // FILD for other targets. 266 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom); 267 } 268 269 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have 270 // this operation. 271 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote); 272 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote); 273 274 if (!UseSoftFloat) { 275 // SSE has no i16 to fp conversion, only i32 276 if (X86ScalarSSEf32) { 277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 278 // f32 and f64 cases are Legal, f80 case is not 279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 280 } else { 281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom); 282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 283 } 284 } else { 285 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 286 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote); 287 } 288 289 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64 290 // are Legal, f80 is custom lowered. 291 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom); 292 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom); 293 294 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have 295 // this operation. 296 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote); 297 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote); 298 299 if (X86ScalarSSEf32) { 300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote); 301 // f32 and f64 cases are Legal, f80 case is not 302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 303 } else { 304 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom); 305 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 306 } 307 308 // Handle FP_TO_UINT by promoting the destination to a larger signed 309 // conversion. 310 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote); 311 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote); 312 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote); 313 314 if (Subtarget->is64Bit()) { 315 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand); 316 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote); 317 } else if (!UseSoftFloat) { 318 if (X86ScalarSSEf32 && !Subtarget->hasSSE3()) 319 // Expand FP_TO_UINT into a select. 320 // FIXME: We would like to use a Custom expander here eventually to do 321 // the optimal thing for SSE vs. the default expansion in the legalizer. 322 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand); 323 else 324 // With SSE3 we can use fisttpll to convert to a signed i64; without 325 // SSE, we're stuck with a fistpll. 326 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom); 327 } 328 329 // TODO: when we have SSE, these could be more efficient, by using movd/movq. 330 if (!X86ScalarSSEf64) { 331 setOperationAction(ISD::BITCAST , MVT::f32 , Expand); 332 setOperationAction(ISD::BITCAST , MVT::i32 , Expand); 333 if (Subtarget->is64Bit()) { 334 setOperationAction(ISD::BITCAST , MVT::f64 , Expand); 335 // Without SSE, i64->f64 goes through memory. 336 setOperationAction(ISD::BITCAST , MVT::i64 , Expand); 337 } 338 } 339 340 // Scalar integer divide and remainder are lowered to use operations that 341 // produce two results, to match the available instructions. This exposes 342 // the two-result form to trivial CSE, which is able to combine x/y and x%y 343 // into a single instruction. 344 // 345 // Scalar integer multiply-high is also lowered to use two-result 346 // operations, to match the available instructions. However, plain multiply 347 // (low) operations are left as Legal, as there are single-result 348 // instructions for this in x86. Using the two-result multiply instructions 349 // when both high and low results are needed must be arranged by dagcombine. 350 for (unsigned i = 0, e = 4; i != e; ++i) { 351 MVT VT = IntVTs[i]; 352 setOperationAction(ISD::MULHS, VT, Expand); 353 setOperationAction(ISD::MULHU, VT, Expand); 354 setOperationAction(ISD::SDIV, VT, Expand); 355 setOperationAction(ISD::UDIV, VT, Expand); 356 setOperationAction(ISD::SREM, VT, Expand); 357 setOperationAction(ISD::UREM, VT, Expand); 358 359 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences. 360 setOperationAction(ISD::ADDC, VT, Custom); 361 setOperationAction(ISD::ADDE, VT, Custom); 362 setOperationAction(ISD::SUBC, VT, Custom); 363 setOperationAction(ISD::SUBE, VT, Custom); 364 } 365 366 setOperationAction(ISD::BR_JT , MVT::Other, Expand); 367 setOperationAction(ISD::BRCOND , MVT::Other, Custom); 368 setOperationAction(ISD::BR_CC , MVT::Other, Expand); 369 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand); 370 if (Subtarget->is64Bit()) 371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal); 373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal); 374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand); 375 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand); 376 setOperationAction(ISD::FREM , MVT::f32 , Expand); 377 setOperationAction(ISD::FREM , MVT::f64 , Expand); 378 setOperationAction(ISD::FREM , MVT::f80 , Expand); 379 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom); 380 381 setOperationAction(ISD::CTTZ , MVT::i8 , Custom); 382 setOperationAction(ISD::CTLZ , MVT::i8 , Custom); 383 setOperationAction(ISD::CTTZ , MVT::i16 , Custom); 384 setOperationAction(ISD::CTLZ , MVT::i16 , Custom); 385 setOperationAction(ISD::CTTZ , MVT::i32 , Custom); 386 setOperationAction(ISD::CTLZ , MVT::i32 , Custom); 387 if (Subtarget->is64Bit()) { 388 setOperationAction(ISD::CTTZ , MVT::i64 , Custom); 389 setOperationAction(ISD::CTLZ , MVT::i64 , Custom); 390 } 391 392 if (Subtarget->hasPOPCNT()) { 393 setOperationAction(ISD::CTPOP , MVT::i8 , Promote); 394 } else { 395 setOperationAction(ISD::CTPOP , MVT::i8 , Expand); 396 setOperationAction(ISD::CTPOP , MVT::i16 , Expand); 397 setOperationAction(ISD::CTPOP , MVT::i32 , Expand); 398 if (Subtarget->is64Bit()) 399 setOperationAction(ISD::CTPOP , MVT::i64 , Expand); 400 } 401 402 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom); 403 setOperationAction(ISD::BSWAP , MVT::i16 , Expand); 404 405 // These should be promoted to a larger select which is supported. 406 setOperationAction(ISD::SELECT , MVT::i1 , Promote); 407 // X86 wants to expand cmov itself. 408 setOperationAction(ISD::SELECT , MVT::i8 , Custom); 409 setOperationAction(ISD::SELECT , MVT::i16 , Custom); 410 setOperationAction(ISD::SELECT , MVT::i32 , Custom); 411 setOperationAction(ISD::SELECT , MVT::f32 , Custom); 412 setOperationAction(ISD::SELECT , MVT::f64 , Custom); 413 setOperationAction(ISD::SELECT , MVT::f80 , Custom); 414 setOperationAction(ISD::SETCC , MVT::i8 , Custom); 415 setOperationAction(ISD::SETCC , MVT::i16 , Custom); 416 setOperationAction(ISD::SETCC , MVT::i32 , Custom); 417 setOperationAction(ISD::SETCC , MVT::f32 , Custom); 418 setOperationAction(ISD::SETCC , MVT::f64 , Custom); 419 setOperationAction(ISD::SETCC , MVT::f80 , Custom); 420 if (Subtarget->is64Bit()) { 421 setOperationAction(ISD::SELECT , MVT::i64 , Custom); 422 setOperationAction(ISD::SETCC , MVT::i64 , Custom); 423 } 424 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom); 425 426 // Darwin ABI issue. 427 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom); 428 setOperationAction(ISD::JumpTable , MVT::i32 , Custom); 429 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom); 430 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom); 431 if (Subtarget->is64Bit()) 432 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 433 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom); 434 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom); 435 if (Subtarget->is64Bit()) { 436 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom); 437 setOperationAction(ISD::JumpTable , MVT::i64 , Custom); 438 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom); 439 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom); 440 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom); 441 } 442 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86) 443 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom); 444 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom); 445 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom); 446 if (Subtarget->is64Bit()) { 447 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom); 448 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom); 449 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom); 450 } 451 452 if (Subtarget->hasXMM()) 453 setOperationAction(ISD::PREFETCH , MVT::Other, Legal); 454 455 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom); 456 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom); 457 458 // On X86 and X86-64, atomic operations are lowered to locked instructions. 459 // Locked instructions, in turn, have implicit fence semantics (all memory 460 // operations are flushed before issuing the locked instruction, and they 461 // are not buffered), so we can fold away the common pattern of 462 // fence-atomic-fence. 463 setShouldFoldAtomicFences(true); 464 465 // Expand certain atomics 466 for (unsigned i = 0, e = 4; i != e; ++i) { 467 MVT VT = IntVTs[i]; 468 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom); 469 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 470 setOperationAction(ISD::ATOMIC_STORE, VT, Custom); 471 } 472 473 if (!Subtarget->is64Bit()) { 474 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom); 475 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom); 476 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 477 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 478 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom); 479 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom); 480 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom); 481 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom); 482 } 483 484 if (Subtarget->hasCmpxchg16b()) { 485 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 486 } 487 488 // FIXME - use subtarget debug flags 489 if (!Subtarget->isTargetDarwin() && 490 !Subtarget->isTargetELF() && 491 !Subtarget->isTargetCygMing()) { 492 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); 493 } 494 495 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand); 496 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand); 497 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand); 498 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand); 499 if (Subtarget->is64Bit()) { 500 setExceptionPointerRegister(X86::RAX); 501 setExceptionSelectorRegister(X86::RDX); 502 } else { 503 setExceptionPointerRegister(X86::EAX); 504 setExceptionSelectorRegister(X86::EDX); 505 } 506 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom); 507 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom); 508 509 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 510 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 511 512 setOperationAction(ISD::TRAP, MVT::Other, Legal); 513 514 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 515 setOperationAction(ISD::VASTART , MVT::Other, Custom); 516 setOperationAction(ISD::VAEND , MVT::Other, Expand); 517 if (Subtarget->is64Bit()) { 518 setOperationAction(ISD::VAARG , MVT::Other, Custom); 519 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 520 } else { 521 setOperationAction(ISD::VAARG , MVT::Other, Expand); 522 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 523 } 524 525 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 526 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 527 528 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 529 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 530 MVT::i64 : MVT::i32, Custom); 531 else if (EnableSegmentedStacks) 532 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 533 MVT::i64 : MVT::i32, Custom); 534 else 535 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 536 MVT::i64 : MVT::i32, Expand); 537 538 if (!UseSoftFloat && X86ScalarSSEf64) { 539 // f32 and f64 use SSE. 540 // Set up the FP register classes. 541 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 542 addRegisterClass(MVT::f64, X86::FR64RegisterClass); 543 544 // Use ANDPD to simulate FABS. 545 setOperationAction(ISD::FABS , MVT::f64, Custom); 546 setOperationAction(ISD::FABS , MVT::f32, Custom); 547 548 // Use XORP to simulate FNEG. 549 setOperationAction(ISD::FNEG , MVT::f64, Custom); 550 setOperationAction(ISD::FNEG , MVT::f32, Custom); 551 552 // Use ANDPD and ORPD to simulate FCOPYSIGN. 553 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 554 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 555 556 // Lower this to FGETSIGNx86 plus an AND. 557 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom); 558 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom); 559 560 // We don't support sin/cos/fmod 561 setOperationAction(ISD::FSIN , MVT::f64, Expand); 562 setOperationAction(ISD::FCOS , MVT::f64, Expand); 563 setOperationAction(ISD::FSIN , MVT::f32, Expand); 564 setOperationAction(ISD::FCOS , MVT::f32, Expand); 565 566 // Expand FP immediates into loads from the stack, except for the special 567 // cases we handle. 568 addLegalFPImmediate(APFloat(+0.0)); // xorpd 569 addLegalFPImmediate(APFloat(+0.0f)); // xorps 570 } else if (!UseSoftFloat && X86ScalarSSEf32) { 571 // Use SSE for f32, x87 for f64. 572 // Set up the FP register classes. 573 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 574 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 575 576 // Use ANDPS to simulate FABS. 577 setOperationAction(ISD::FABS , MVT::f32, Custom); 578 579 // Use XORP to simulate FNEG. 580 setOperationAction(ISD::FNEG , MVT::f32, Custom); 581 582 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 583 584 // Use ANDPS and ORPS to simulate FCOPYSIGN. 585 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 586 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 587 588 // We don't support sin/cos/fmod 589 setOperationAction(ISD::FSIN , MVT::f32, Expand); 590 setOperationAction(ISD::FCOS , MVT::f32, Expand); 591 592 // Special cases we handle for FP constants. 593 addLegalFPImmediate(APFloat(+0.0f)); // xorps 594 addLegalFPImmediate(APFloat(+0.0)); // FLD0 595 addLegalFPImmediate(APFloat(+1.0)); // FLD1 596 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 597 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 598 599 if (!UnsafeFPMath) { 600 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 601 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 602 } 603 } else if (!UseSoftFloat) { 604 // f32 and f64 in x87. 605 // Set up the FP register classes. 606 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 607 addRegisterClass(MVT::f32, X86::RFP32RegisterClass); 608 609 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 610 setOperationAction(ISD::UNDEF, MVT::f32, Expand); 611 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 612 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 613 614 if (!UnsafeFPMath) { 615 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 616 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 617 } 618 addLegalFPImmediate(APFloat(+0.0)); // FLD0 619 addLegalFPImmediate(APFloat(+1.0)); // FLD1 620 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 621 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 622 addLegalFPImmediate(APFloat(+0.0f)); // FLD0 623 addLegalFPImmediate(APFloat(+1.0f)); // FLD1 624 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS 625 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS 626 } 627 628 // We don't support FMA. 629 setOperationAction(ISD::FMA, MVT::f64, Expand); 630 setOperationAction(ISD::FMA, MVT::f32, Expand); 631 632 // Long double always uses X87. 633 if (!UseSoftFloat) { 634 addRegisterClass(MVT::f80, X86::RFP80RegisterClass); 635 setOperationAction(ISD::UNDEF, MVT::f80, Expand); 636 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand); 637 { 638 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended); 639 addLegalFPImmediate(TmpFlt); // FLD0 640 TmpFlt.changeSign(); 641 addLegalFPImmediate(TmpFlt); // FLD0/FCHS 642 643 bool ignored; 644 APFloat TmpFlt2(+1.0); 645 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, 646 &ignored); 647 addLegalFPImmediate(TmpFlt2); // FLD1 648 TmpFlt2.changeSign(); 649 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS 650 } 651 652 if (!UnsafeFPMath) { 653 setOperationAction(ISD::FSIN , MVT::f80 , Expand); 654 setOperationAction(ISD::FCOS , MVT::f80 , Expand); 655 } 656 657 setOperationAction(ISD::FMA, MVT::f80, Expand); 658 } 659 660 // Always use a library call for pow. 661 setOperationAction(ISD::FPOW , MVT::f32 , Expand); 662 setOperationAction(ISD::FPOW , MVT::f64 , Expand); 663 setOperationAction(ISD::FPOW , MVT::f80 , Expand); 664 665 setOperationAction(ISD::FLOG, MVT::f80, Expand); 666 setOperationAction(ISD::FLOG2, MVT::f80, Expand); 667 setOperationAction(ISD::FLOG10, MVT::f80, Expand); 668 setOperationAction(ISD::FEXP, MVT::f80, Expand); 669 setOperationAction(ISD::FEXP2, MVT::f80, Expand); 670 671 // First set operation action for all vector types to either promote 672 // (for widening) or expand (for scalarization). Then we will selectively 673 // turn on ones that can be effectively codegen'd. 674 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 675 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) { 676 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand); 677 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand); 678 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand); 679 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand); 680 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand); 681 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand); 682 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand); 683 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand); 684 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand); 685 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand); 686 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand); 687 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand); 688 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand); 689 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand); 690 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand); 691 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand); 692 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 693 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 694 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand); 695 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand); 696 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand); 697 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand); 698 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand); 699 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand); 700 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand); 701 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 702 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 703 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand); 704 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand); 705 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand); 706 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand); 707 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand); 708 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand); 709 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand); 710 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand); 711 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand); 712 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand); 713 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand); 714 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand); 715 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand); 716 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand); 717 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand); 718 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand); 719 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand); 720 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand); 721 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand); 722 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand); 723 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 724 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 725 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand); 726 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand); 727 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand); 728 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand); 729 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand); 730 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 731 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 732 setTruncStoreAction((MVT::SimpleValueType)VT, 733 (MVT::SimpleValueType)InnerVT, Expand); 734 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand); 735 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand); 736 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand); 737 } 738 739 // FIXME: In order to prevent SSE instructions being expanded to MMX ones 740 // with -msoft-float, disable use of MMX as well. 741 if (!UseSoftFloat && Subtarget->hasMMX()) { 742 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass); 743 // No operations on x86mmx supported, everything uses intrinsics. 744 } 745 746 // MMX-sized vectors (other than x86mmx) are expected to be expanded 747 // into smaller operations. 748 setOperationAction(ISD::MULHS, MVT::v8i8, Expand); 749 setOperationAction(ISD::MULHS, MVT::v4i16, Expand); 750 setOperationAction(ISD::MULHS, MVT::v2i32, Expand); 751 setOperationAction(ISD::MULHS, MVT::v1i64, Expand); 752 setOperationAction(ISD::AND, MVT::v8i8, Expand); 753 setOperationAction(ISD::AND, MVT::v4i16, Expand); 754 setOperationAction(ISD::AND, MVT::v2i32, Expand); 755 setOperationAction(ISD::AND, MVT::v1i64, Expand); 756 setOperationAction(ISD::OR, MVT::v8i8, Expand); 757 setOperationAction(ISD::OR, MVT::v4i16, Expand); 758 setOperationAction(ISD::OR, MVT::v2i32, Expand); 759 setOperationAction(ISD::OR, MVT::v1i64, Expand); 760 setOperationAction(ISD::XOR, MVT::v8i8, Expand); 761 setOperationAction(ISD::XOR, MVT::v4i16, Expand); 762 setOperationAction(ISD::XOR, MVT::v2i32, Expand); 763 setOperationAction(ISD::XOR, MVT::v1i64, Expand); 764 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand); 765 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand); 766 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand); 767 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand); 768 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand); 769 setOperationAction(ISD::SELECT, MVT::v8i8, Expand); 770 setOperationAction(ISD::SELECT, MVT::v4i16, Expand); 771 setOperationAction(ISD::SELECT, MVT::v2i32, Expand); 772 setOperationAction(ISD::SELECT, MVT::v1i64, Expand); 773 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand); 774 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand); 775 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand); 776 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand); 777 778 if (!UseSoftFloat && Subtarget->hasXMM()) { 779 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass); 780 781 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 782 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 783 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 784 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 785 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 786 setOperationAction(ISD::FNEG, MVT::v4f32, Custom); 787 setOperationAction(ISD::LOAD, MVT::v4f32, Legal); 788 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 789 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom); 790 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 791 setOperationAction(ISD::SELECT, MVT::v4f32, Custom); 792 setOperationAction(ISD::SETCC, MVT::v4f32, Custom); 793 } 794 795 if (!UseSoftFloat && Subtarget->hasXMMInt()) { 796 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass); 797 798 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM 799 // registers cannot be used even for integer operations. 800 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass); 801 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass); 802 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass); 803 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass); 804 805 setOperationAction(ISD::ADD, MVT::v16i8, Legal); 806 setOperationAction(ISD::ADD, MVT::v8i16, Legal); 807 setOperationAction(ISD::ADD, MVT::v4i32, Legal); 808 setOperationAction(ISD::ADD, MVT::v2i64, Legal); 809 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 810 setOperationAction(ISD::SUB, MVT::v16i8, Legal); 811 setOperationAction(ISD::SUB, MVT::v8i16, Legal); 812 setOperationAction(ISD::SUB, MVT::v4i32, Legal); 813 setOperationAction(ISD::SUB, MVT::v2i64, Legal); 814 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 815 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 816 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 817 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 818 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 819 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 820 setOperationAction(ISD::FNEG, MVT::v2f64, Custom); 821 822 setOperationAction(ISD::SETCC, MVT::v2f64, Custom); 823 setOperationAction(ISD::SETCC, MVT::v16i8, Custom); 824 setOperationAction(ISD::SETCC, MVT::v8i16, Custom); 825 setOperationAction(ISD::SETCC, MVT::v4i32, Custom); 826 827 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom); 828 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom); 829 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 830 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 831 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 832 833 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom); 834 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom); 835 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom); 836 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom); 837 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom); 838 839 // Custom lower build_vector, vector_shuffle, and extract_vector_elt. 840 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) { 841 EVT VT = (MVT::SimpleValueType)i; 842 // Do not attempt to custom lower non-power-of-2 vectors 843 if (!isPowerOf2_32(VT.getVectorNumElements())) 844 continue; 845 // Do not attempt to custom lower non-128-bit vectors 846 if (!VT.is128BitVector()) 847 continue; 848 setOperationAction(ISD::BUILD_VECTOR, 849 VT.getSimpleVT().SimpleTy, Custom); 850 setOperationAction(ISD::VECTOR_SHUFFLE, 851 VT.getSimpleVT().SimpleTy, Custom); 852 setOperationAction(ISD::EXTRACT_VECTOR_ELT, 853 VT.getSimpleVT().SimpleTy, Custom); 854 } 855 856 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 857 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 858 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 859 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 860 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 861 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 862 863 if (Subtarget->is64Bit()) { 864 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 865 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 866 } 867 868 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 869 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) { 870 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 871 EVT VT = SVT; 872 873 // Do not attempt to promote non-128-bit vectors 874 if (!VT.is128BitVector()) 875 continue; 876 877 setOperationAction(ISD::AND, SVT, Promote); 878 AddPromotedToType (ISD::AND, SVT, MVT::v2i64); 879 setOperationAction(ISD::OR, SVT, Promote); 880 AddPromotedToType (ISD::OR, SVT, MVT::v2i64); 881 setOperationAction(ISD::XOR, SVT, Promote); 882 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64); 883 setOperationAction(ISD::LOAD, SVT, Promote); 884 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64); 885 setOperationAction(ISD::SELECT, SVT, Promote); 886 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64); 887 } 888 889 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 890 891 // Custom lower v2i64 and v2f64 selects. 892 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 893 setOperationAction(ISD::LOAD, MVT::v2i64, Legal); 894 setOperationAction(ISD::SELECT, MVT::v2f64, Custom); 895 setOperationAction(ISD::SELECT, MVT::v2i64, Custom); 896 897 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 898 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 899 } 900 901 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) { 902 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 903 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 904 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 905 setOperationAction(ISD::FRINT, MVT::f32, Legal); 906 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 907 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 908 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 909 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 910 setOperationAction(ISD::FRINT, MVT::f64, Legal); 911 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 912 913 // FIXME: Do we need to handle scalar-to-vector here? 914 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 915 916 // Can turn SHL into an integer multiply. 917 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 918 setOperationAction(ISD::SHL, MVT::v16i8, Custom); 919 920 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom); 921 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom); 922 setOperationAction(ISD::VSELECT, MVT::v16i8, Custom); 923 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom); 924 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom); 925 926 // i8 and i16 vectors are custom , because the source register and source 927 // source memory operand types are not the same width. f32 vectors are 928 // custom since the immediate controlling the insert encodes additional 929 // information. 930 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 931 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 932 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 933 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 934 935 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom); 936 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom); 937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom); 938 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 939 940 if (Subtarget->is64Bit()) { 941 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal); 942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 943 } 944 } 945 946 if (Subtarget->hasSSE2() || Subtarget->hasAVX()) { 947 setOperationAction(ISD::SRL, MVT::v2i64, Custom); 948 setOperationAction(ISD::SRL, MVT::v4i32, Custom); 949 setOperationAction(ISD::SRL, MVT::v16i8, Custom); 950 setOperationAction(ISD::SRL, MVT::v8i16, Custom); 951 952 setOperationAction(ISD::SHL, MVT::v2i64, Custom); 953 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 954 setOperationAction(ISD::SHL, MVT::v8i16, Custom); 955 956 setOperationAction(ISD::SRA, MVT::v4i32, Custom); 957 setOperationAction(ISD::SRA, MVT::v8i16, Custom); 958 } 959 960 if (Subtarget->hasSSE42() || Subtarget->hasAVX()) 961 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 962 963 if (!UseSoftFloat && Subtarget->hasAVX()) { 964 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass); 965 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass); 966 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass); 967 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass); 968 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass); 969 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass); 970 971 setOperationAction(ISD::LOAD, MVT::v8f32, Legal); 972 setOperationAction(ISD::LOAD, MVT::v4f64, Legal); 973 setOperationAction(ISD::LOAD, MVT::v4i64, Legal); 974 975 setOperationAction(ISD::FADD, MVT::v8f32, Legal); 976 setOperationAction(ISD::FSUB, MVT::v8f32, Legal); 977 setOperationAction(ISD::FMUL, MVT::v8f32, Legal); 978 setOperationAction(ISD::FDIV, MVT::v8f32, Legal); 979 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal); 980 setOperationAction(ISD::FNEG, MVT::v8f32, Custom); 981 982 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 983 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 984 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 985 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 986 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 987 setOperationAction(ISD::FNEG, MVT::v4f64, Custom); 988 989 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal); 990 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal); 991 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal); 992 993 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom); 994 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom); 995 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom); 996 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom); 997 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom); 998 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom); 999 1000 setOperationAction(ISD::SRL, MVT::v4i64, Custom); 1001 setOperationAction(ISD::SRL, MVT::v8i32, Custom); 1002 setOperationAction(ISD::SRL, MVT::v16i16, Custom); 1003 setOperationAction(ISD::SRL, MVT::v32i8, Custom); 1004 1005 setOperationAction(ISD::SHL, MVT::v4i64, Custom); 1006 setOperationAction(ISD::SHL, MVT::v8i32, Custom); 1007 setOperationAction(ISD::SHL, MVT::v16i16, Custom); 1008 setOperationAction(ISD::SHL, MVT::v32i8, Custom); 1009 1010 setOperationAction(ISD::SRA, MVT::v8i32, Custom); 1011 setOperationAction(ISD::SRA, MVT::v16i16, Custom); 1012 1013 setOperationAction(ISD::SETCC, MVT::v32i8, Custom); 1014 setOperationAction(ISD::SETCC, MVT::v16i16, Custom); 1015 setOperationAction(ISD::SETCC, MVT::v8i32, Custom); 1016 setOperationAction(ISD::SETCC, MVT::v4i64, Custom); 1017 1018 setOperationAction(ISD::SELECT, MVT::v4f64, Custom); 1019 setOperationAction(ISD::SELECT, MVT::v4i64, Custom); 1020 setOperationAction(ISD::SELECT, MVT::v8f32, Custom); 1021 1022 setOperationAction(ISD::ADD, MVT::v4i64, Custom); 1023 setOperationAction(ISD::ADD, MVT::v8i32, Custom); 1024 setOperationAction(ISD::ADD, MVT::v16i16, Custom); 1025 setOperationAction(ISD::ADD, MVT::v32i8, Custom); 1026 1027 setOperationAction(ISD::SUB, MVT::v4i64, Custom); 1028 setOperationAction(ISD::SUB, MVT::v8i32, Custom); 1029 setOperationAction(ISD::SUB, MVT::v16i16, Custom); 1030 setOperationAction(ISD::SUB, MVT::v32i8, Custom); 1031 1032 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1033 setOperationAction(ISD::MUL, MVT::v8i32, Custom); 1034 setOperationAction(ISD::MUL, MVT::v16i16, Custom); 1035 // Don't lower v32i8 because there is no 128-bit byte mul 1036 1037 // Custom lower several nodes for 256-bit types. 1038 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1039 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) { 1040 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 1041 EVT VT = SVT; 1042 1043 // Extract subvector is special because the value type 1044 // (result) is 128-bit but the source is 256-bit wide. 1045 if (VT.is128BitVector()) 1046 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom); 1047 1048 // Do not attempt to custom lower other non-256-bit vectors 1049 if (!VT.is256BitVector()) 1050 continue; 1051 1052 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom); 1053 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom); 1054 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom); 1055 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom); 1056 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom); 1057 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom); 1058 } 1059 1060 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64. 1061 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) { 1062 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 1063 EVT VT = SVT; 1064 1065 // Do not attempt to promote non-256-bit vectors 1066 if (!VT.is256BitVector()) 1067 continue; 1068 1069 setOperationAction(ISD::AND, SVT, Promote); 1070 AddPromotedToType (ISD::AND, SVT, MVT::v4i64); 1071 setOperationAction(ISD::OR, SVT, Promote); 1072 AddPromotedToType (ISD::OR, SVT, MVT::v4i64); 1073 setOperationAction(ISD::XOR, SVT, Promote); 1074 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64); 1075 setOperationAction(ISD::LOAD, SVT, Promote); 1076 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64); 1077 setOperationAction(ISD::SELECT, SVT, Promote); 1078 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64); 1079 } 1080 } 1081 1082 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion 1083 // of this type with custom code. 1084 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1085 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) { 1086 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom); 1087 } 1088 1089 // We want to custom lower some of our intrinsics. 1090 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1091 1092 1093 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't 1094 // handle type legalization for these operations here. 1095 // 1096 // FIXME: We really should do custom legalization for addition and 1097 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better 1098 // than generic legalization for 64-bit multiplication-with-overflow, though. 1099 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) { 1100 // Add/Sub/Mul with overflow operations are custom lowered. 1101 MVT VT = IntVTs[i]; 1102 setOperationAction(ISD::SADDO, VT, Custom); 1103 setOperationAction(ISD::UADDO, VT, Custom); 1104 setOperationAction(ISD::SSUBO, VT, Custom); 1105 setOperationAction(ISD::USUBO, VT, Custom); 1106 setOperationAction(ISD::SMULO, VT, Custom); 1107 setOperationAction(ISD::UMULO, VT, Custom); 1108 } 1109 1110 // There are no 8-bit 3-address imul/mul instructions 1111 setOperationAction(ISD::SMULO, MVT::i8, Expand); 1112 setOperationAction(ISD::UMULO, MVT::i8, Expand); 1113 1114 if (!Subtarget->is64Bit()) { 1115 // These libcalls are not available in 32-bit. 1116 setLibcallName(RTLIB::SHL_I128, 0); 1117 setLibcallName(RTLIB::SRL_I128, 0); 1118 setLibcallName(RTLIB::SRA_I128, 0); 1119 } 1120 1121 // We have target-specific dag combine patterns for the following nodes: 1122 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1123 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 1124 setTargetDAGCombine(ISD::BUILD_VECTOR); 1125 setTargetDAGCombine(ISD::SELECT); 1126 setTargetDAGCombine(ISD::SHL); 1127 setTargetDAGCombine(ISD::SRA); 1128 setTargetDAGCombine(ISD::SRL); 1129 setTargetDAGCombine(ISD::OR); 1130 setTargetDAGCombine(ISD::AND); 1131 setTargetDAGCombine(ISD::ADD); 1132 setTargetDAGCombine(ISD::SUB); 1133 setTargetDAGCombine(ISD::STORE); 1134 setTargetDAGCombine(ISD::ZERO_EXTEND); 1135 setTargetDAGCombine(ISD::SINT_TO_FP); 1136 if (Subtarget->is64Bit()) 1137 setTargetDAGCombine(ISD::MUL); 1138 1139 computeRegisterProperties(); 1140 1141 // On Darwin, -Os means optimize for size without hurting performance, 1142 // do not reduce the limit. 1143 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores 1144 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8; 1145 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores 1146 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1147 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores 1148 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1149 setPrefLoopAlignment(16); 1150 benefitFromCodePlacementOpt = true; 1151 1152 setPrefFunctionAlignment(4); 1153} 1154 1155 1156EVT X86TargetLowering::getSetCCResultType(EVT VT) const { 1157 if (!VT.isVector()) return MVT::i8; 1158 return VT.changeVectorElementTypeToInteger(); 1159} 1160 1161 1162/// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1163/// the desired ByVal argument alignment. 1164static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) { 1165 if (MaxAlign == 16) 1166 return; 1167 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1168 if (VTy->getBitWidth() == 128) 1169 MaxAlign = 16; 1170 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1171 unsigned EltAlign = 0; 1172 getMaxByValAlign(ATy->getElementType(), EltAlign); 1173 if (EltAlign > MaxAlign) 1174 MaxAlign = EltAlign; 1175 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1176 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1177 unsigned EltAlign = 0; 1178 getMaxByValAlign(STy->getElementType(i), EltAlign); 1179 if (EltAlign > MaxAlign) 1180 MaxAlign = EltAlign; 1181 if (MaxAlign == 16) 1182 break; 1183 } 1184 } 1185 return; 1186} 1187 1188/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1189/// function arguments in the caller parameter area. For X86, aggregates 1190/// that contain SSE vectors are placed at 16-byte boundaries while the rest 1191/// are at 4-byte boundaries. 1192unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const { 1193 if (Subtarget->is64Bit()) { 1194 // Max of 8 and alignment of type. 1195 unsigned TyAlign = TD->getABITypeAlignment(Ty); 1196 if (TyAlign > 8) 1197 return TyAlign; 1198 return 8; 1199 } 1200 1201 unsigned Align = 4; 1202 if (Subtarget->hasXMM()) 1203 getMaxByValAlign(Ty, Align); 1204 return Align; 1205} 1206 1207/// getOptimalMemOpType - Returns the target specific optimal type for load 1208/// and store operations as a result of memset, memcpy, and memmove 1209/// lowering. If DstAlign is zero that means it's safe to destination 1210/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 1211/// means there isn't a need to check it against alignment requirement, 1212/// probably because the source does not need to be loaded. If 1213/// 'NonScalarIntSafe' is true, that means it's safe to return a 1214/// non-scalar-integer type, e.g. empty string source, constant, or loaded 1215/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is 1216/// constant so it does not need to be loaded. 1217/// It returns EVT::Other if the type should be determined using generic 1218/// target-independent logic. 1219EVT 1220X86TargetLowering::getOptimalMemOpType(uint64_t Size, 1221 unsigned DstAlign, unsigned SrcAlign, 1222 bool NonScalarIntSafe, 1223 bool MemcpyStrSrc, 1224 MachineFunction &MF) const { 1225 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like 1226 // linux. This is because the stack realignment code can't handle certain 1227 // cases like PR2962. This should be removed when PR2962 is fixed. 1228 const Function *F = MF.getFunction(); 1229 if (NonScalarIntSafe && 1230 !F->hasFnAttr(Attribute::NoImplicitFloat)) { 1231 if (Size >= 16 && 1232 (Subtarget->isUnalignedMemAccessFast() || 1233 ((DstAlign == 0 || DstAlign >= 16) && 1234 (SrcAlign == 0 || SrcAlign >= 16))) && 1235 Subtarget->getStackAlignment() >= 16) { 1236 if (Subtarget->hasSSE2()) 1237 return MVT::v4i32; 1238 if (Subtarget->hasSSE1()) 1239 return MVT::v4f32; 1240 } else if (!MemcpyStrSrc && Size >= 8 && 1241 !Subtarget->is64Bit() && 1242 Subtarget->getStackAlignment() >= 8 && 1243 Subtarget->hasXMMInt()) { 1244 // Do not use f64 to lower memcpy if source is string constant. It's 1245 // better to use i32 to avoid the loads. 1246 return MVT::f64; 1247 } 1248 } 1249 if (Subtarget->is64Bit() && Size >= 8) 1250 return MVT::i64; 1251 return MVT::i32; 1252} 1253 1254/// getJumpTableEncoding - Return the entry encoding for a jump table in the 1255/// current function. The returned value is a member of the 1256/// MachineJumpTableInfo::JTEntryKind enum. 1257unsigned X86TargetLowering::getJumpTableEncoding() const { 1258 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF 1259 // symbol. 1260 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1261 Subtarget->isPICStyleGOT()) 1262 return MachineJumpTableInfo::EK_Custom32; 1263 1264 // Otherwise, use the normal jump table encoding heuristics. 1265 return TargetLowering::getJumpTableEncoding(); 1266} 1267 1268const MCExpr * 1269X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 1270 const MachineBasicBlock *MBB, 1271 unsigned uid,MCContext &Ctx) const{ 1272 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1273 Subtarget->isPICStyleGOT()); 1274 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF 1275 // entries. 1276 return MCSymbolRefExpr::Create(MBB->getSymbol(), 1277 MCSymbolRefExpr::VK_GOTOFF, Ctx); 1278} 1279 1280/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 1281/// jumptable. 1282SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table, 1283 SelectionDAG &DAG) const { 1284 if (!Subtarget->is64Bit()) 1285 // This doesn't have DebugLoc associated with it, but is not really the 1286 // same as a Register. 1287 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy()); 1288 return Table; 1289} 1290 1291/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 1292/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 1293/// MCExpr. 1294const MCExpr *X86TargetLowering:: 1295getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, 1296 MCContext &Ctx) const { 1297 // X86-64 uses RIP relative addressing based on the jump table label. 1298 if (Subtarget->isPICStyleRIPRel()) 1299 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 1300 1301 // Otherwise, the reference is relative to the PIC base. 1302 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx); 1303} 1304 1305// FIXME: Why this routine is here? Move to RegInfo! 1306std::pair<const TargetRegisterClass*, uint8_t> 1307X86TargetLowering::findRepresentativeClass(EVT VT) const{ 1308 const TargetRegisterClass *RRC = 0; 1309 uint8_t Cost = 1; 1310 switch (VT.getSimpleVT().SimpleTy) { 1311 default: 1312 return TargetLowering::findRepresentativeClass(VT); 1313 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64: 1314 RRC = (Subtarget->is64Bit() 1315 ? X86::GR64RegisterClass : X86::GR32RegisterClass); 1316 break; 1317 case MVT::x86mmx: 1318 RRC = X86::VR64RegisterClass; 1319 break; 1320 case MVT::f32: case MVT::f64: 1321 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1322 case MVT::v4f32: case MVT::v2f64: 1323 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32: 1324 case MVT::v4f64: 1325 RRC = X86::VR128RegisterClass; 1326 break; 1327 } 1328 return std::make_pair(RRC, Cost); 1329} 1330 1331bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace, 1332 unsigned &Offset) const { 1333 if (!Subtarget->isTargetLinux()) 1334 return false; 1335 1336 if (Subtarget->is64Bit()) { 1337 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs: 1338 Offset = 0x28; 1339 if (getTargetMachine().getCodeModel() == CodeModel::Kernel) 1340 AddressSpace = 256; 1341 else 1342 AddressSpace = 257; 1343 } else { 1344 // %gs:0x14 on i386 1345 Offset = 0x14; 1346 AddressSpace = 256; 1347 } 1348 return true; 1349} 1350 1351 1352//===----------------------------------------------------------------------===// 1353// Return Value Calling Convention Implementation 1354//===----------------------------------------------------------------------===// 1355 1356#include "X86GenCallingConv.inc" 1357 1358bool 1359X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, 1360 MachineFunction &MF, bool isVarArg, 1361 const SmallVectorImpl<ISD::OutputArg> &Outs, 1362 LLVMContext &Context) const { 1363 SmallVector<CCValAssign, 16> RVLocs; 1364 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1365 RVLocs, Context); 1366 return CCInfo.CheckReturn(Outs, RetCC_X86); 1367} 1368 1369SDValue 1370X86TargetLowering::LowerReturn(SDValue Chain, 1371 CallingConv::ID CallConv, bool isVarArg, 1372 const SmallVectorImpl<ISD::OutputArg> &Outs, 1373 const SmallVectorImpl<SDValue> &OutVals, 1374 DebugLoc dl, SelectionDAG &DAG) const { 1375 MachineFunction &MF = DAG.getMachineFunction(); 1376 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1377 1378 SmallVector<CCValAssign, 16> RVLocs; 1379 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1380 RVLocs, *DAG.getContext()); 1381 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1382 1383 // Add the regs to the liveout set for the function. 1384 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1385 for (unsigned i = 0; i != RVLocs.size(); ++i) 1386 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg())) 1387 MRI.addLiveOut(RVLocs[i].getLocReg()); 1388 1389 SDValue Flag; 1390 1391 SmallVector<SDValue, 6> RetOps; 1392 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1393 // Operand #1 = Bytes To Pop 1394 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), 1395 MVT::i16)); 1396 1397 // Copy the result values into the output registers. 1398 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1399 CCValAssign &VA = RVLocs[i]; 1400 assert(VA.isRegLoc() && "Can only return in registers!"); 1401 SDValue ValToCopy = OutVals[i]; 1402 EVT ValVT = ValToCopy.getValueType(); 1403 1404 // If this is x86-64, and we disabled SSE, we can't return FP values, 1405 // or SSE or MMX vectors. 1406 if ((ValVT == MVT::f32 || ValVT == MVT::f64 || 1407 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && 1408 (Subtarget->is64Bit() && !Subtarget->hasXMM())) { 1409 report_fatal_error("SSE register return with SSE disabled"); 1410 } 1411 // Likewise we can't return F64 values with SSE1 only. gcc does so, but 1412 // llvm-gcc has never done it right and no one has noticed, so this 1413 // should be OK for now. 1414 if (ValVT == MVT::f64 && 1415 (Subtarget->is64Bit() && !Subtarget->hasXMMInt())) 1416 report_fatal_error("SSE2 register return with SSE2 disabled"); 1417 1418 // Returns in ST0/ST1 are handled specially: these are pushed as operands to 1419 // the RET instruction and handled by the FP Stackifier. 1420 if (VA.getLocReg() == X86::ST0 || 1421 VA.getLocReg() == X86::ST1) { 1422 // If this is a copy from an xmm register to ST(0), use an FPExtend to 1423 // change the value to the FP stack register class. 1424 if (isScalarFPTypeInSSEReg(VA.getValVT())) 1425 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy); 1426 RetOps.push_back(ValToCopy); 1427 // Don't emit a copytoreg. 1428 continue; 1429 } 1430 1431 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64 1432 // which is returned in RAX / RDX. 1433 if (Subtarget->is64Bit()) { 1434 if (ValVT == MVT::x86mmx) { 1435 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1436 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy); 1437 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 1438 ValToCopy); 1439 // If we don't have SSE2 available, convert to v4f32 so the generated 1440 // register is legal. 1441 if (!Subtarget->hasSSE2()) 1442 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy); 1443 } 1444 } 1445 } 1446 1447 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag); 1448 Flag = Chain.getValue(1); 1449 } 1450 1451 // The x86-64 ABI for returning structs by value requires that we copy 1452 // the sret argument into %rax for the return. We saved the argument into 1453 // a virtual register in the entry block, so now we copy the value out 1454 // and into %rax. 1455 if (Subtarget->is64Bit() && 1456 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) { 1457 MachineFunction &MF = DAG.getMachineFunction(); 1458 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1459 unsigned Reg = FuncInfo->getSRetReturnReg(); 1460 assert(Reg && 1461 "SRetReturnReg should have been set in LowerFormalArguments()."); 1462 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy()); 1463 1464 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag); 1465 Flag = Chain.getValue(1); 1466 1467 // RAX now acts like a return value. 1468 MRI.addLiveOut(X86::RAX); 1469 } 1470 1471 RetOps[0] = Chain; // Update chain. 1472 1473 // Add the flag if we have it. 1474 if (Flag.getNode()) 1475 RetOps.push_back(Flag); 1476 1477 return DAG.getNode(X86ISD::RET_FLAG, dl, 1478 MVT::Other, &RetOps[0], RetOps.size()); 1479} 1480 1481bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const { 1482 if (N->getNumValues() != 1) 1483 return false; 1484 if (!N->hasNUsesOfValue(1, 0)) 1485 return false; 1486 1487 SDNode *Copy = *N->use_begin(); 1488 if (Copy->getOpcode() != ISD::CopyToReg && 1489 Copy->getOpcode() != ISD::FP_EXTEND) 1490 return false; 1491 1492 bool HasRet = false; 1493 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 1494 UI != UE; ++UI) { 1495 if (UI->getOpcode() != X86ISD::RET_FLAG) 1496 return false; 1497 HasRet = true; 1498 } 1499 1500 return HasRet; 1501} 1502 1503EVT 1504X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT, 1505 ISD::NodeType ExtendKind) const { 1506 MVT ReturnMVT; 1507 // TODO: Is this also valid on 32-bit? 1508 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND) 1509 ReturnMVT = MVT::i8; 1510 else 1511 ReturnMVT = MVT::i32; 1512 1513 EVT MinVT = getRegisterType(Context, ReturnMVT); 1514 return VT.bitsLT(MinVT) ? MinVT : VT; 1515} 1516 1517/// LowerCallResult - Lower the result values of a call into the 1518/// appropriate copies out of appropriate physical registers. 1519/// 1520SDValue 1521X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1522 CallingConv::ID CallConv, bool isVarArg, 1523 const SmallVectorImpl<ISD::InputArg> &Ins, 1524 DebugLoc dl, SelectionDAG &DAG, 1525 SmallVectorImpl<SDValue> &InVals) const { 1526 1527 // Assign locations to each value returned by this call. 1528 SmallVector<CCValAssign, 16> RVLocs; 1529 bool Is64Bit = Subtarget->is64Bit(); 1530 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1531 getTargetMachine(), RVLocs, *DAG.getContext()); 1532 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 1533 1534 // Copy all of the result registers out of their specified physreg. 1535 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1536 CCValAssign &VA = RVLocs[i]; 1537 EVT CopyVT = VA.getValVT(); 1538 1539 // If this is x86-64, and we disabled SSE, we can't return FP values 1540 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 1541 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) { 1542 report_fatal_error("SSE register return with SSE disabled"); 1543 } 1544 1545 SDValue Val; 1546 1547 // If this is a call to a function that returns an fp value on the floating 1548 // point stack, we must guarantee the the value is popped from the stack, so 1549 // a CopyFromReg is not good enough - the copy instruction may be eliminated 1550 // if the return value is not used. We use the FpPOP_RETVAL instruction 1551 // instead. 1552 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 1553 // If we prefer to use the value in xmm registers, copy it out as f80 and 1554 // use a truncate to move it from fp stack reg to xmm reg. 1555 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80; 1556 SDValue Ops[] = { Chain, InFlag }; 1557 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT, 1558 MVT::Other, MVT::Glue, Ops, 2), 1); 1559 Val = Chain.getValue(0); 1560 1561 // Round the f80 to the right size, which also moves it to the appropriate 1562 // xmm register. 1563 if (CopyVT != VA.getValVT()) 1564 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val, 1565 // This truncation won't change the value. 1566 DAG.getIntPtrConstant(1)); 1567 } else { 1568 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1569 CopyVT, InFlag).getValue(1); 1570 Val = Chain.getValue(0); 1571 } 1572 InFlag = Chain.getValue(2); 1573 InVals.push_back(Val); 1574 } 1575 1576 return Chain; 1577} 1578 1579 1580//===----------------------------------------------------------------------===// 1581// C & StdCall & Fast Calling Convention implementation 1582//===----------------------------------------------------------------------===// 1583// StdCall calling convention seems to be standard for many Windows' API 1584// routines and around. It differs from C calling convention just a little: 1585// callee should clean up the stack, not caller. Symbols should be also 1586// decorated in some fancy way :) It doesn't support any vector arguments. 1587// For info on fast calling convention see Fast Calling Convention (tail call) 1588// implementation LowerX86_32FastCCCallTo. 1589 1590/// CallIsStructReturn - Determines whether a call uses struct return 1591/// semantics. 1592static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) { 1593 if (Outs.empty()) 1594 return false; 1595 1596 return Outs[0].Flags.isSRet(); 1597} 1598 1599/// ArgsAreStructReturn - Determines whether a function uses struct 1600/// return semantics. 1601static bool 1602ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) { 1603 if (Ins.empty()) 1604 return false; 1605 1606 return Ins[0].Flags.isSRet(); 1607} 1608 1609/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 1610/// by "Src" to address "Dst" with size and alignment information specified by 1611/// the specific parameter attribute. The copy will be passed as a byval 1612/// function parameter. 1613static SDValue 1614CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 1615 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 1616 DebugLoc dl) { 1617 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 1618 1619 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 1620 /*isVolatile*/false, /*AlwaysInline=*/true, 1621 MachinePointerInfo(), MachinePointerInfo()); 1622} 1623 1624/// IsTailCallConvention - Return true if the calling convention is one that 1625/// supports tail call optimization. 1626static bool IsTailCallConvention(CallingConv::ID CC) { 1627 return (CC == CallingConv::Fast || CC == CallingConv::GHC); 1628} 1629 1630bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 1631 if (!CI->isTailCall()) 1632 return false; 1633 1634 CallSite CS(CI); 1635 CallingConv::ID CalleeCC = CS.getCallingConv(); 1636 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C) 1637 return false; 1638 1639 return true; 1640} 1641 1642/// FuncIsMadeTailCallSafe - Return true if the function is being made into 1643/// a tailcall target by changing its ABI. 1644static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) { 1645 return GuaranteedTailCallOpt && IsTailCallConvention(CC); 1646} 1647 1648SDValue 1649X86TargetLowering::LowerMemArgument(SDValue Chain, 1650 CallingConv::ID CallConv, 1651 const SmallVectorImpl<ISD::InputArg> &Ins, 1652 DebugLoc dl, SelectionDAG &DAG, 1653 const CCValAssign &VA, 1654 MachineFrameInfo *MFI, 1655 unsigned i) const { 1656 // Create the nodes corresponding to a load from this parameter slot. 1657 ISD::ArgFlagsTy Flags = Ins[i].Flags; 1658 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv); 1659 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal(); 1660 EVT ValVT; 1661 1662 // If value is passed by pointer we have address passed instead of the value 1663 // itself. 1664 if (VA.getLocInfo() == CCValAssign::Indirect) 1665 ValVT = VA.getLocVT(); 1666 else 1667 ValVT = VA.getValVT(); 1668 1669 // FIXME: For now, all byval parameter objects are marked mutable. This can be 1670 // changed with more analysis. 1671 // In case of tail call optimization mark all arguments mutable. Since they 1672 // could be overwritten by lowering of arguments in case of a tail call. 1673 if (Flags.isByVal()) { 1674 unsigned Bytes = Flags.getByValSize(); 1675 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects. 1676 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable); 1677 return DAG.getFrameIndex(FI, getPointerTy()); 1678 } else { 1679 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8, 1680 VA.getLocMemOffset(), isImmutable); 1681 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 1682 return DAG.getLoad(ValVT, dl, Chain, FIN, 1683 MachinePointerInfo::getFixedStack(FI), 1684 false, false, 0); 1685 } 1686} 1687 1688SDValue 1689X86TargetLowering::LowerFormalArguments(SDValue Chain, 1690 CallingConv::ID CallConv, 1691 bool isVarArg, 1692 const SmallVectorImpl<ISD::InputArg> &Ins, 1693 DebugLoc dl, 1694 SelectionDAG &DAG, 1695 SmallVectorImpl<SDValue> &InVals) 1696 const { 1697 MachineFunction &MF = DAG.getMachineFunction(); 1698 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1699 1700 const Function* Fn = MF.getFunction(); 1701 if (Fn->hasExternalLinkage() && 1702 Subtarget->isTargetCygMing() && 1703 Fn->getName() == "main") 1704 FuncInfo->setForceFramePointer(true); 1705 1706 MachineFrameInfo *MFI = MF.getFrameInfo(); 1707 bool Is64Bit = Subtarget->is64Bit(); 1708 bool IsWin64 = Subtarget->isTargetWin64(); 1709 1710 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1711 "Var args not supported with calling convention fastcc or ghc"); 1712 1713 // Assign locations to all of the incoming arguments. 1714 SmallVector<CCValAssign, 16> ArgLocs; 1715 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1716 ArgLocs, *DAG.getContext()); 1717 1718 // Allocate shadow area for Win64 1719 if (IsWin64) { 1720 CCInfo.AllocateStack(32, 8); 1721 } 1722 1723 CCInfo.AnalyzeFormalArguments(Ins, CC_X86); 1724 1725 unsigned LastVal = ~0U; 1726 SDValue ArgValue; 1727 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1728 CCValAssign &VA = ArgLocs[i]; 1729 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later 1730 // places. 1731 assert(VA.getValNo() != LastVal && 1732 "Don't support value assigned to multiple locs yet"); 1733 LastVal = VA.getValNo(); 1734 1735 if (VA.isRegLoc()) { 1736 EVT RegVT = VA.getLocVT(); 1737 TargetRegisterClass *RC = NULL; 1738 if (RegVT == MVT::i32) 1739 RC = X86::GR32RegisterClass; 1740 else if (Is64Bit && RegVT == MVT::i64) 1741 RC = X86::GR64RegisterClass; 1742 else if (RegVT == MVT::f32) 1743 RC = X86::FR32RegisterClass; 1744 else if (RegVT == MVT::f64) 1745 RC = X86::FR64RegisterClass; 1746 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256) 1747 RC = X86::VR256RegisterClass; 1748 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128) 1749 RC = X86::VR128RegisterClass; 1750 else if (RegVT == MVT::x86mmx) 1751 RC = X86::VR64RegisterClass; 1752 else 1753 llvm_unreachable("Unknown argument type!"); 1754 1755 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 1756 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 1757 1758 // If this is an 8 or 16-bit value, it is really passed promoted to 32 1759 // bits. Insert an assert[sz]ext to capture this, then truncate to the 1760 // right size. 1761 if (VA.getLocInfo() == CCValAssign::SExt) 1762 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 1763 DAG.getValueType(VA.getValVT())); 1764 else if (VA.getLocInfo() == CCValAssign::ZExt) 1765 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 1766 DAG.getValueType(VA.getValVT())); 1767 else if (VA.getLocInfo() == CCValAssign::BCvt) 1768 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 1769 1770 if (VA.isExtInLoc()) { 1771 // Handle MMX values passed in XMM regs. 1772 if (RegVT.isVector()) { 1773 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), 1774 ArgValue); 1775 } else 1776 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1777 } 1778 } else { 1779 assert(VA.isMemLoc()); 1780 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i); 1781 } 1782 1783 // If value is passed via pointer - do a load. 1784 if (VA.getLocInfo() == CCValAssign::Indirect) 1785 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, 1786 MachinePointerInfo(), false, false, 0); 1787 1788 InVals.push_back(ArgValue); 1789 } 1790 1791 // The x86-64 ABI for returning structs by value requires that we copy 1792 // the sret argument into %rax for the return. Save the argument into 1793 // a virtual register so that we can access it from the return points. 1794 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) { 1795 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1796 unsigned Reg = FuncInfo->getSRetReturnReg(); 1797 if (!Reg) { 1798 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64)); 1799 FuncInfo->setSRetReturnReg(Reg); 1800 } 1801 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]); 1802 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain); 1803 } 1804 1805 unsigned StackSize = CCInfo.getNextStackOffset(); 1806 // Align stack specially for tail calls. 1807 if (FuncIsMadeTailCallSafe(CallConv)) 1808 StackSize = GetAlignedArgumentStackSize(StackSize, DAG); 1809 1810 // If the function takes variable number of arguments, make a frame index for 1811 // the start of the first vararg value... for expansion of llvm.va_start. 1812 if (isVarArg) { 1813 if (Is64Bit || (CallConv != CallingConv::X86_FastCall && 1814 CallConv != CallingConv::X86_ThisCall)) { 1815 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true)); 1816 } 1817 if (Is64Bit) { 1818 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0; 1819 1820 // FIXME: We should really autogenerate these arrays 1821 static const unsigned GPR64ArgRegsWin64[] = { 1822 X86::RCX, X86::RDX, X86::R8, X86::R9 1823 }; 1824 static const unsigned GPR64ArgRegs64Bit[] = { 1825 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9 1826 }; 1827 static const unsigned XMMArgRegs64Bit[] = { 1828 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 1829 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 1830 }; 1831 const unsigned *GPR64ArgRegs; 1832 unsigned NumXMMRegs = 0; 1833 1834 if (IsWin64) { 1835 // The XMM registers which might contain var arg parameters are shadowed 1836 // in their paired GPR. So we only need to save the GPR to their home 1837 // slots. 1838 TotalNumIntRegs = 4; 1839 GPR64ArgRegs = GPR64ArgRegsWin64; 1840 } else { 1841 TotalNumIntRegs = 6; TotalNumXMMRegs = 8; 1842 GPR64ArgRegs = GPR64ArgRegs64Bit; 1843 1844 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs); 1845 } 1846 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 1847 TotalNumIntRegs); 1848 1849 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat); 1850 assert(!(NumXMMRegs && !Subtarget->hasXMM()) && 1851 "SSE register cannot be used when SSE is disabled!"); 1852 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) && 1853 "SSE register cannot be used when SSE is disabled!"); 1854 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM()) 1855 // Kernel mode asks for SSE to be disabled, so don't push them 1856 // on the stack. 1857 TotalNumXMMRegs = 0; 1858 1859 if (IsWin64) { 1860 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering(); 1861 // Get to the caller-allocated home save location. Add 8 to account 1862 // for the return address. 1863 int HomeOffset = TFI.getOffsetOfLocalArea() + 8; 1864 FuncInfo->setRegSaveFrameIndex( 1865 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false)); 1866 // Fixup to set vararg frame on shadow area (4 x i64). 1867 if (NumIntRegs < 4) 1868 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex()); 1869 } else { 1870 // For X86-64, if there are vararg parameters that are passed via 1871 // registers, then we must store them to their spots on the stack so they 1872 // may be loaded by deferencing the result of va_next. 1873 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8); 1874 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16); 1875 FuncInfo->setRegSaveFrameIndex( 1876 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16, 1877 false)); 1878 } 1879 1880 // Store the integer parameter registers. 1881 SmallVector<SDValue, 8> MemOps; 1882 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 1883 getPointerTy()); 1884 unsigned Offset = FuncInfo->getVarArgsGPOffset(); 1885 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) { 1886 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN, 1887 DAG.getIntPtrConstant(Offset)); 1888 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs], 1889 X86::GR64RegisterClass); 1890 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 1891 SDValue Store = 1892 DAG.getStore(Val.getValue(1), dl, Val, FIN, 1893 MachinePointerInfo::getFixedStack( 1894 FuncInfo->getRegSaveFrameIndex(), Offset), 1895 false, false, 0); 1896 MemOps.push_back(Store); 1897 Offset += 8; 1898 } 1899 1900 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) { 1901 // Now store the XMM (fp + vector) parameter registers. 1902 SmallVector<SDValue, 11> SaveXMMOps; 1903 SaveXMMOps.push_back(Chain); 1904 1905 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass); 1906 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8); 1907 SaveXMMOps.push_back(ALVal); 1908 1909 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1910 FuncInfo->getRegSaveFrameIndex())); 1911 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1912 FuncInfo->getVarArgsFPOffset())); 1913 1914 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) { 1915 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs], 1916 X86::VR128RegisterClass); 1917 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32); 1918 SaveXMMOps.push_back(Val); 1919 } 1920 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, 1921 MVT::Other, 1922 &SaveXMMOps[0], SaveXMMOps.size())); 1923 } 1924 1925 if (!MemOps.empty()) 1926 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 1927 &MemOps[0], MemOps.size()); 1928 } 1929 } 1930 1931 // Some CCs need callee pop. 1932 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) { 1933 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything. 1934 } else { 1935 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing. 1936 // If this is an sret function, the return should pop the hidden pointer. 1937 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins)) 1938 FuncInfo->setBytesToPopOnReturn(4); 1939 } 1940 1941 if (!Is64Bit) { 1942 // RegSaveFrameIndex is X86-64 only. 1943 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA); 1944 if (CallConv == CallingConv::X86_FastCall || 1945 CallConv == CallingConv::X86_ThisCall) 1946 // fastcc functions can't have varargs. 1947 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA); 1948 } 1949 1950 FuncInfo->setArgumentStackSize(StackSize); 1951 1952 return Chain; 1953} 1954 1955SDValue 1956X86TargetLowering::LowerMemOpCallTo(SDValue Chain, 1957 SDValue StackPtr, SDValue Arg, 1958 DebugLoc dl, SelectionDAG &DAG, 1959 const CCValAssign &VA, 1960 ISD::ArgFlagsTy Flags) const { 1961 unsigned LocMemOffset = VA.getLocMemOffset(); 1962 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 1963 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 1964 if (Flags.isByVal()) 1965 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl); 1966 1967 return DAG.getStore(Chain, dl, Arg, PtrOff, 1968 MachinePointerInfo::getStack(LocMemOffset), 1969 false, false, 0); 1970} 1971 1972/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call 1973/// optimization is performed and it is required. 1974SDValue 1975X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 1976 SDValue &OutRetAddr, SDValue Chain, 1977 bool IsTailCall, bool Is64Bit, 1978 int FPDiff, DebugLoc dl) const { 1979 // Adjust the Return address stack slot. 1980 EVT VT = getPointerTy(); 1981 OutRetAddr = getReturnAddressFrameIndex(DAG); 1982 1983 // Load the "old" Return address. 1984 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(), 1985 false, false, 0); 1986 return SDValue(OutRetAddr.getNode(), 1); 1987} 1988 1989/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call 1990/// optimization is performed and it is required (FPDiff!=0). 1991static SDValue 1992EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 1993 SDValue Chain, SDValue RetAddrFrIdx, 1994 bool Is64Bit, int FPDiff, DebugLoc dl) { 1995 // Store the return address to the appropriate stack slot. 1996 if (!FPDiff) return Chain; 1997 // Calculate the new stack slot for the return address. 1998 int SlotSize = Is64Bit ? 8 : 4; 1999 int NewReturnAddrFI = 2000 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false); 2001 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2002 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT); 2003 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx, 2004 MachinePointerInfo::getFixedStack(NewReturnAddrFI), 2005 false, false, 0); 2006 return Chain; 2007} 2008 2009SDValue 2010X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee, 2011 CallingConv::ID CallConv, bool isVarArg, 2012 bool &isTailCall, 2013 const SmallVectorImpl<ISD::OutputArg> &Outs, 2014 const SmallVectorImpl<SDValue> &OutVals, 2015 const SmallVectorImpl<ISD::InputArg> &Ins, 2016 DebugLoc dl, SelectionDAG &DAG, 2017 SmallVectorImpl<SDValue> &InVals) const { 2018 MachineFunction &MF = DAG.getMachineFunction(); 2019 bool Is64Bit = Subtarget->is64Bit(); 2020 bool IsWin64 = Subtarget->isTargetWin64(); 2021 bool IsStructRet = CallIsStructReturn(Outs); 2022 bool IsSibcall = false; 2023 2024 if (isTailCall) { 2025 // Check if it's really possible to do a tail call. 2026 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 2027 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(), 2028 Outs, OutVals, Ins, DAG); 2029 2030 // Sibcalls are automatically detected tailcalls which do not require 2031 // ABI changes. 2032 if (!GuaranteedTailCallOpt && isTailCall) 2033 IsSibcall = true; 2034 2035 if (isTailCall) 2036 ++NumTailCalls; 2037 } 2038 2039 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 2040 "Var args not supported with calling convention fastcc or ghc"); 2041 2042 // Analyze operands of the call, assigning locations to each operand. 2043 SmallVector<CCValAssign, 16> ArgLocs; 2044 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 2045 ArgLocs, *DAG.getContext()); 2046 2047 // Allocate shadow area for Win64 2048 if (IsWin64) { 2049 CCInfo.AllocateStack(32, 8); 2050 } 2051 2052 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2053 2054 // Get a count of how many bytes are to be pushed on the stack. 2055 unsigned NumBytes = CCInfo.getNextStackOffset(); 2056 if (IsSibcall) 2057 // This is a sibcall. The memory operands are available in caller's 2058 // own caller's stack. 2059 NumBytes = 0; 2060 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv)) 2061 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG); 2062 2063 int FPDiff = 0; 2064 if (isTailCall && !IsSibcall) { 2065 // Lower arguments at fp - stackoffset + fpdiff. 2066 unsigned NumBytesCallerPushed = 2067 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn(); 2068 FPDiff = NumBytesCallerPushed - NumBytes; 2069 2070 // Set the delta of movement of the returnaddr stackslot. 2071 // But only set if delta is greater than previous delta. 2072 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta())) 2073 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff); 2074 } 2075 2076 if (!IsSibcall) 2077 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true)); 2078 2079 SDValue RetAddrFrIdx; 2080 // Load return address for tail calls. 2081 if (isTailCall && FPDiff) 2082 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, 2083 Is64Bit, FPDiff, dl); 2084 2085 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2086 SmallVector<SDValue, 8> MemOpChains; 2087 SDValue StackPtr; 2088 2089 // Walk the register/memloc assignments, inserting copies/loads. In the case 2090 // of tail call optimization arguments are handle later. 2091 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2092 CCValAssign &VA = ArgLocs[i]; 2093 EVT RegVT = VA.getLocVT(); 2094 SDValue Arg = OutVals[i]; 2095 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2096 bool isByVal = Flags.isByVal(); 2097 2098 // Promote the value if needed. 2099 switch (VA.getLocInfo()) { 2100 default: llvm_unreachable("Unknown loc info!"); 2101 case CCValAssign::Full: break; 2102 case CCValAssign::SExt: 2103 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg); 2104 break; 2105 case CCValAssign::ZExt: 2106 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg); 2107 break; 2108 case CCValAssign::AExt: 2109 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) { 2110 // Special case: passing MMX values in XMM registers. 2111 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 2112 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg); 2113 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg); 2114 } else 2115 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg); 2116 break; 2117 case CCValAssign::BCvt: 2118 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg); 2119 break; 2120 case CCValAssign::Indirect: { 2121 // Store the argument. 2122 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT()); 2123 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2124 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot, 2125 MachinePointerInfo::getFixedStack(FI), 2126 false, false, 0); 2127 Arg = SpillSlot; 2128 break; 2129 } 2130 } 2131 2132 if (VA.isRegLoc()) { 2133 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2134 if (isVarArg && IsWin64) { 2135 // Win64 ABI requires argument XMM reg to be copied to the corresponding 2136 // shadow reg if callee is a varargs function. 2137 unsigned ShadowReg = 0; 2138 switch (VA.getLocReg()) { 2139 case X86::XMM0: ShadowReg = X86::RCX; break; 2140 case X86::XMM1: ShadowReg = X86::RDX; break; 2141 case X86::XMM2: ShadowReg = X86::R8; break; 2142 case X86::XMM3: ShadowReg = X86::R9; break; 2143 } 2144 if (ShadowReg) 2145 RegsToPass.push_back(std::make_pair(ShadowReg, Arg)); 2146 } 2147 } else if (!IsSibcall && (!isTailCall || isByVal)) { 2148 assert(VA.isMemLoc()); 2149 if (StackPtr.getNode() == 0) 2150 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy()); 2151 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2152 dl, DAG, VA, Flags)); 2153 } 2154 } 2155 2156 if (!MemOpChains.empty()) 2157 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2158 &MemOpChains[0], MemOpChains.size()); 2159 2160 // Build a sequence of copy-to-reg nodes chained together with token chain 2161 // and flag operands which copy the outgoing args into registers. 2162 SDValue InFlag; 2163 // Tail call byval lowering might overwrite argument registers so in case of 2164 // tail call optimization the copies to registers are lowered later. 2165 if (!isTailCall) 2166 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2167 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2168 RegsToPass[i].second, InFlag); 2169 InFlag = Chain.getValue(1); 2170 } 2171 2172 if (Subtarget->isPICStyleGOT()) { 2173 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2174 // GOT pointer. 2175 if (!isTailCall) { 2176 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX, 2177 DAG.getNode(X86ISD::GlobalBaseReg, 2178 DebugLoc(), getPointerTy()), 2179 InFlag); 2180 InFlag = Chain.getValue(1); 2181 } else { 2182 // If we are tail calling and generating PIC/GOT style code load the 2183 // address of the callee into ECX. The value in ecx is used as target of 2184 // the tail jump. This is done to circumvent the ebx/callee-saved problem 2185 // for tail calls on PIC/GOT architectures. Normally we would just put the 2186 // address of GOT into ebx and then call target@PLT. But for tail calls 2187 // ebx would be restored (since ebx is callee saved) before jumping to the 2188 // target@PLT. 2189 2190 // Note: The actual moving to ECX is done further down. 2191 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 2192 if (G && !G->getGlobal()->hasHiddenVisibility() && 2193 !G->getGlobal()->hasProtectedVisibility()) 2194 Callee = LowerGlobalAddress(Callee, DAG); 2195 else if (isa<ExternalSymbolSDNode>(Callee)) 2196 Callee = LowerExternalSymbol(Callee, DAG); 2197 } 2198 } 2199 2200 if (Is64Bit && isVarArg && !IsWin64) { 2201 // From AMD64 ABI document: 2202 // For calls that may call functions that use varargs or stdargs 2203 // (prototype-less calls or calls to functions containing ellipsis (...) in 2204 // the declaration) %al is used as hidden argument to specify the number 2205 // of SSE registers used. The contents of %al do not need to match exactly 2206 // the number of registers, but must be an ubound on the number of SSE 2207 // registers used and is in the range 0 - 8 inclusive. 2208 2209 // Count the number of XMM registers allocated. 2210 static const unsigned XMMArgRegs[] = { 2211 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2212 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2213 }; 2214 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2215 assert((Subtarget->hasXMM() || !NumXMMRegs) 2216 && "SSE registers cannot be used when SSE is disabled"); 2217 2218 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, 2219 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag); 2220 InFlag = Chain.getValue(1); 2221 } 2222 2223 2224 // For tail calls lower the arguments to the 'real' stack slot. 2225 if (isTailCall) { 2226 // Force all the incoming stack arguments to be loaded from the stack 2227 // before any new outgoing arguments are stored to the stack, because the 2228 // outgoing stack slots may alias the incoming argument stack slots, and 2229 // the alias isn't otherwise explicit. This is slightly more conservative 2230 // than necessary, because it means that each store effectively depends 2231 // on every argument instead of just those arguments it would clobber. 2232 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain); 2233 2234 SmallVector<SDValue, 8> MemOpChains2; 2235 SDValue FIN; 2236 int FI = 0; 2237 // Do not flag preceding copytoreg stuff together with the following stuff. 2238 InFlag = SDValue(); 2239 if (GuaranteedTailCallOpt) { 2240 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2241 CCValAssign &VA = ArgLocs[i]; 2242 if (VA.isRegLoc()) 2243 continue; 2244 assert(VA.isMemLoc()); 2245 SDValue Arg = OutVals[i]; 2246 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2247 // Create frame index. 2248 int32_t Offset = VA.getLocMemOffset()+FPDiff; 2249 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8; 2250 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2251 FIN = DAG.getFrameIndex(FI, getPointerTy()); 2252 2253 if (Flags.isByVal()) { 2254 // Copy relative to framepointer. 2255 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset()); 2256 if (StackPtr.getNode() == 0) 2257 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, 2258 getPointerTy()); 2259 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source); 2260 2261 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, 2262 ArgChain, 2263 Flags, DAG, dl)); 2264 } else { 2265 // Store relative to framepointer. 2266 MemOpChains2.push_back( 2267 DAG.getStore(ArgChain, dl, Arg, FIN, 2268 MachinePointerInfo::getFixedStack(FI), 2269 false, false, 0)); 2270 } 2271 } 2272 } 2273 2274 if (!MemOpChains2.empty()) 2275 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2276 &MemOpChains2[0], MemOpChains2.size()); 2277 2278 // Copy arguments to their registers. 2279 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2280 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2281 RegsToPass[i].second, InFlag); 2282 InFlag = Chain.getValue(1); 2283 } 2284 InFlag =SDValue(); 2285 2286 // Store the return address to the appropriate stack slot. 2287 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit, 2288 FPDiff, dl); 2289 } 2290 2291 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 2292 assert(Is64Bit && "Large code model is only legal in 64-bit mode."); 2293 // In the 64-bit large code model, we have to make all calls 2294 // through a register, since the call instruction's 32-bit 2295 // pc-relative offset may not be large enough to hold the whole 2296 // address. 2297 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2298 // If the callee is a GlobalAddress node (quite common, every direct call 2299 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack 2300 // it. 2301 2302 // We should use extra load for direct calls to dllimported functions in 2303 // non-JIT mode. 2304 const GlobalValue *GV = G->getGlobal(); 2305 if (!GV->hasDLLImportLinkage()) { 2306 unsigned char OpFlags = 0; 2307 bool ExtraLoad = false; 2308 unsigned WrapperKind = ISD::DELETED_NODE; 2309 2310 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2311 // external symbols most go through the PLT in PIC mode. If the symbol 2312 // has hidden or protected visibility, or if it is static or local, then 2313 // we don't need to use the PLT - we can directly call it. 2314 if (Subtarget->isTargetELF() && 2315 getTargetMachine().getRelocationModel() == Reloc::PIC_ && 2316 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2317 OpFlags = X86II::MO_PLT; 2318 } else if (Subtarget->isPICStyleStubAny() && 2319 (GV->isDeclaration() || GV->isWeakForLinker()) && 2320 (!Subtarget->getTargetTriple().isMacOSX() || 2321 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2322 // PC-relative references to external symbols should go through $stub, 2323 // unless we're building with the leopard linker or later, which 2324 // automatically synthesizes these stubs. 2325 OpFlags = X86II::MO_DARWIN_STUB; 2326 } else if (Subtarget->isPICStyleRIPRel() && 2327 isa<Function>(GV) && 2328 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) { 2329 // If the function is marked as non-lazy, generate an indirect call 2330 // which loads from the GOT directly. This avoids runtime overhead 2331 // at the cost of eager binding (and one extra byte of encoding). 2332 OpFlags = X86II::MO_GOTPCREL; 2333 WrapperKind = X86ISD::WrapperRIP; 2334 ExtraLoad = true; 2335 } 2336 2337 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 2338 G->getOffset(), OpFlags); 2339 2340 // Add a wrapper if needed. 2341 if (WrapperKind != ISD::DELETED_NODE) 2342 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee); 2343 // Add extra indirection if needed. 2344 if (ExtraLoad) 2345 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee, 2346 MachinePointerInfo::getGOT(), 2347 false, false, 0); 2348 } 2349 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2350 unsigned char OpFlags = 0; 2351 2352 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to 2353 // external symbols should go through the PLT. 2354 if (Subtarget->isTargetELF() && 2355 getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2356 OpFlags = X86II::MO_PLT; 2357 } else if (Subtarget->isPICStyleStubAny() && 2358 (!Subtarget->getTargetTriple().isMacOSX() || 2359 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2360 // PC-relative references to external symbols should go through $stub, 2361 // unless we're building with the leopard linker or later, which 2362 // automatically synthesizes these stubs. 2363 OpFlags = X86II::MO_DARWIN_STUB; 2364 } 2365 2366 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(), 2367 OpFlags); 2368 } 2369 2370 // Returns a chain & a flag for retval copy to use. 2371 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2372 SmallVector<SDValue, 8> Ops; 2373 2374 if (!IsSibcall && isTailCall) { 2375 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2376 DAG.getIntPtrConstant(0, true), InFlag); 2377 InFlag = Chain.getValue(1); 2378 } 2379 2380 Ops.push_back(Chain); 2381 Ops.push_back(Callee); 2382 2383 if (isTailCall) 2384 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32)); 2385 2386 // Add argument registers to the end of the list so that they are known live 2387 // into the call. 2388 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2389 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2390 RegsToPass[i].second.getValueType())); 2391 2392 // Add an implicit use GOT pointer in EBX. 2393 if (!isTailCall && Subtarget->isPICStyleGOT()) 2394 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy())); 2395 2396 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions. 2397 if (Is64Bit && isVarArg && !IsWin64) 2398 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8)); 2399 2400 if (InFlag.getNode()) 2401 Ops.push_back(InFlag); 2402 2403 if (isTailCall) { 2404 // We used to do: 2405 //// If this is the first return lowered for this function, add the regs 2406 //// to the liveout set for the function. 2407 // This isn't right, although it's probably harmless on x86; liveouts 2408 // should be computed from returns not tail calls. Consider a void 2409 // function making a tail call to a function returning int. 2410 return DAG.getNode(X86ISD::TC_RETURN, dl, 2411 NodeTys, &Ops[0], Ops.size()); 2412 } 2413 2414 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); 2415 InFlag = Chain.getValue(1); 2416 2417 // Create the CALLSEQ_END node. 2418 unsigned NumBytesForCalleeToPush; 2419 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) 2420 NumBytesForCalleeToPush = NumBytes; // Callee pops everything 2421 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet) 2422 // If this is a call to a struct-return function, the callee 2423 // pops the hidden struct pointer, so we have to push it back. 2424 // This is common for Darwin/X86, Linux & Mingw32 targets. 2425 NumBytesForCalleeToPush = 4; 2426 else 2427 NumBytesForCalleeToPush = 0; // Callee pops nothing. 2428 2429 // Returns a flag for retval copy to use. 2430 if (!IsSibcall) { 2431 Chain = DAG.getCALLSEQ_END(Chain, 2432 DAG.getIntPtrConstant(NumBytes, true), 2433 DAG.getIntPtrConstant(NumBytesForCalleeToPush, 2434 true), 2435 InFlag); 2436 InFlag = Chain.getValue(1); 2437 } 2438 2439 // Handle result values, copying them out of physregs into vregs that we 2440 // return. 2441 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2442 Ins, dl, DAG, InVals); 2443} 2444 2445 2446//===----------------------------------------------------------------------===// 2447// Fast Calling Convention (tail call) implementation 2448//===----------------------------------------------------------------------===// 2449 2450// Like std call, callee cleans arguments, convention except that ECX is 2451// reserved for storing the tail called function address. Only 2 registers are 2452// free for argument passing (inreg). Tail call optimization is performed 2453// provided: 2454// * tailcallopt is enabled 2455// * caller/callee are fastcc 2456// On X86_64 architecture with GOT-style position independent code only local 2457// (within module) calls are supported at the moment. 2458// To keep the stack aligned according to platform abi the function 2459// GetAlignedArgumentStackSize ensures that argument delta is always multiples 2460// of stack alignment. (Dynamic linkers need this - darwin's dyld for example) 2461// If a tail called function callee has more arguments than the caller the 2462// caller needs to make sure that there is room to move the RETADDR to. This is 2463// achieved by reserving an area the size of the argument delta right after the 2464// original REtADDR, but before the saved framepointer or the spilled registers 2465// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4) 2466// stack layout: 2467// arg1 2468// arg2 2469// RETADDR 2470// [ new RETADDR 2471// move area ] 2472// (possible EBP) 2473// ESI 2474// EDI 2475// local1 .. 2476 2477/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned 2478/// for a 16 byte align requirement. 2479unsigned 2480X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 2481 SelectionDAG& DAG) const { 2482 MachineFunction &MF = DAG.getMachineFunction(); 2483 const TargetMachine &TM = MF.getTarget(); 2484 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 2485 unsigned StackAlignment = TFI.getStackAlignment(); 2486 uint64_t AlignMask = StackAlignment - 1; 2487 int64_t Offset = StackSize; 2488 uint64_t SlotSize = TD->getPointerSize(); 2489 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) { 2490 // Number smaller than 12 so just add the difference. 2491 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask)); 2492 } else { 2493 // Mask out lower bits, add stackalignment once plus the 12 bytes. 2494 Offset = ((~AlignMask) & Offset) + StackAlignment + 2495 (StackAlignment-SlotSize); 2496 } 2497 return Offset; 2498} 2499 2500/// MatchingStackOffset - Return true if the given stack call argument is 2501/// already available in the same position (relatively) of the caller's 2502/// incoming argument stack. 2503static 2504bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2505 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2506 const X86InstrInfo *TII) { 2507 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2508 int FI = INT_MAX; 2509 if (Arg.getOpcode() == ISD::CopyFromReg) { 2510 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2511 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2512 return false; 2513 MachineInstr *Def = MRI->getVRegDef(VR); 2514 if (!Def) 2515 return false; 2516 if (!Flags.isByVal()) { 2517 if (!TII->isLoadFromStackSlot(Def, FI)) 2518 return false; 2519 } else { 2520 unsigned Opcode = Def->getOpcode(); 2521 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) && 2522 Def->getOperand(1).isFI()) { 2523 FI = Def->getOperand(1).getIndex(); 2524 Bytes = Flags.getByValSize(); 2525 } else 2526 return false; 2527 } 2528 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2529 if (Flags.isByVal()) 2530 // ByVal argument is passed in as a pointer but it's now being 2531 // dereferenced. e.g. 2532 // define @foo(%struct.X* %A) { 2533 // tail call @bar(%struct.X* byval %A) 2534 // } 2535 return false; 2536 SDValue Ptr = Ld->getBasePtr(); 2537 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2538 if (!FINode) 2539 return false; 2540 FI = FINode->getIndex(); 2541 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) { 2542 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg); 2543 FI = FINode->getIndex(); 2544 Bytes = Flags.getByValSize(); 2545 } else 2546 return false; 2547 2548 assert(FI != INT_MAX); 2549 if (!MFI->isFixedObjectIndex(FI)) 2550 return false; 2551 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2552} 2553 2554/// IsEligibleForTailCallOptimization - Check whether the call is eligible 2555/// for tail call optimization. Targets which want to do tail call 2556/// optimization should implement this function. 2557bool 2558X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2559 CallingConv::ID CalleeCC, 2560 bool isVarArg, 2561 bool isCalleeStructRet, 2562 bool isCallerStructRet, 2563 const SmallVectorImpl<ISD::OutputArg> &Outs, 2564 const SmallVectorImpl<SDValue> &OutVals, 2565 const SmallVectorImpl<ISD::InputArg> &Ins, 2566 SelectionDAG& DAG) const { 2567 if (!IsTailCallConvention(CalleeCC) && 2568 CalleeCC != CallingConv::C) 2569 return false; 2570 2571 // If -tailcallopt is specified, make fastcc functions tail-callable. 2572 const MachineFunction &MF = DAG.getMachineFunction(); 2573 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2574 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2575 bool CCMatch = CallerCC == CalleeCC; 2576 2577 if (GuaranteedTailCallOpt) { 2578 if (IsTailCallConvention(CalleeCC) && CCMatch) 2579 return true; 2580 return false; 2581 } 2582 2583 // Look for obvious safe cases to perform tail call optimization that do not 2584 // require ABI changes. This is what gcc calls sibcall. 2585 2586 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to 2587 // emit a special epilogue. 2588 if (RegInfo->needsStackRealignment(MF)) 2589 return false; 2590 2591 // Also avoid sibcall optimization if either caller or callee uses struct 2592 // return semantics. 2593 if (isCalleeStructRet || isCallerStructRet) 2594 return false; 2595 2596 // An stdcall caller is expected to clean up its arguments; the callee 2597 // isn't going to do that. 2598 if (!CCMatch && CallerCC==CallingConv::X86_StdCall) 2599 return false; 2600 2601 // Do not sibcall optimize vararg calls unless all arguments are passed via 2602 // registers. 2603 if (isVarArg && !Outs.empty()) { 2604 2605 // Optimizing for varargs on Win64 is unlikely to be safe without 2606 // additional testing. 2607 if (Subtarget->isTargetWin64()) 2608 return false; 2609 2610 SmallVector<CCValAssign, 16> ArgLocs; 2611 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2612 getTargetMachine(), ArgLocs, *DAG.getContext()); 2613 2614 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2615 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) 2616 if (!ArgLocs[i].isRegLoc()) 2617 return false; 2618 } 2619 2620 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack. 2621 // Therefore if it's not used by the call it is not safe to optimize this into 2622 // a sibcall. 2623 bool Unused = false; 2624 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 2625 if (!Ins[i].Used) { 2626 Unused = true; 2627 break; 2628 } 2629 } 2630 if (Unused) { 2631 SmallVector<CCValAssign, 16> RVLocs; 2632 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), 2633 getTargetMachine(), RVLocs, *DAG.getContext()); 2634 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 2635 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 2636 CCValAssign &VA = RVLocs[i]; 2637 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 2638 return false; 2639 } 2640 } 2641 2642 // If the calling conventions do not match, then we'd better make sure the 2643 // results are returned in the same way as what the caller expects. 2644 if (!CCMatch) { 2645 SmallVector<CCValAssign, 16> RVLocs1; 2646 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), 2647 getTargetMachine(), RVLocs1, *DAG.getContext()); 2648 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86); 2649 2650 SmallVector<CCValAssign, 16> RVLocs2; 2651 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), 2652 getTargetMachine(), RVLocs2, *DAG.getContext()); 2653 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86); 2654 2655 if (RVLocs1.size() != RVLocs2.size()) 2656 return false; 2657 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2658 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2659 return false; 2660 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2661 return false; 2662 if (RVLocs1[i].isRegLoc()) { 2663 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2664 return false; 2665 } else { 2666 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2667 return false; 2668 } 2669 } 2670 } 2671 2672 // If the callee takes no arguments then go on to check the results of the 2673 // call. 2674 if (!Outs.empty()) { 2675 // Check if stack adjustment is needed. For now, do not do this if any 2676 // argument is passed on the stack. 2677 SmallVector<CCValAssign, 16> ArgLocs; 2678 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2679 getTargetMachine(), ArgLocs, *DAG.getContext()); 2680 2681 // Allocate shadow area for Win64 2682 if (Subtarget->isTargetWin64()) { 2683 CCInfo.AllocateStack(32, 8); 2684 } 2685 2686 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2687 if (CCInfo.getNextStackOffset()) { 2688 MachineFunction &MF = DAG.getMachineFunction(); 2689 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) 2690 return false; 2691 2692 // Check if the arguments are already laid out in the right way as 2693 // the caller's fixed stack objects. 2694 MachineFrameInfo *MFI = MF.getFrameInfo(); 2695 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2696 const X86InstrInfo *TII = 2697 ((X86TargetMachine&)getTargetMachine()).getInstrInfo(); 2698 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2699 CCValAssign &VA = ArgLocs[i]; 2700 SDValue Arg = OutVals[i]; 2701 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2702 if (VA.getLocInfo() == CCValAssign::Indirect) 2703 return false; 2704 if (!VA.isRegLoc()) { 2705 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2706 MFI, MRI, TII)) 2707 return false; 2708 } 2709 } 2710 } 2711 2712 // If the tailcall address may be in a register, then make sure it's 2713 // possible to register allocate for it. In 32-bit, the call address can 2714 // only target EAX, EDX, or ECX since the tail call must be scheduled after 2715 // callee-saved registers are restored. These happen to be the same 2716 // registers used to pass 'inreg' arguments so watch out for those. 2717 if (!Subtarget->is64Bit() && 2718 !isa<GlobalAddressSDNode>(Callee) && 2719 !isa<ExternalSymbolSDNode>(Callee)) { 2720 unsigned NumInRegs = 0; 2721 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2722 CCValAssign &VA = ArgLocs[i]; 2723 if (!VA.isRegLoc()) 2724 continue; 2725 unsigned Reg = VA.getLocReg(); 2726 switch (Reg) { 2727 default: break; 2728 case X86::EAX: case X86::EDX: case X86::ECX: 2729 if (++NumInRegs == 3) 2730 return false; 2731 break; 2732 } 2733 } 2734 } 2735 } 2736 2737 return true; 2738} 2739 2740FastISel * 2741X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const { 2742 return X86::createFastISel(funcInfo); 2743} 2744 2745 2746//===----------------------------------------------------------------------===// 2747// Other Lowering Hooks 2748//===----------------------------------------------------------------------===// 2749 2750static bool MayFoldLoad(SDValue Op) { 2751 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode()); 2752} 2753 2754static bool MayFoldIntoStore(SDValue Op) { 2755 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin()); 2756} 2757 2758static bool isTargetShuffle(unsigned Opcode) { 2759 switch(Opcode) { 2760 default: return false; 2761 case X86ISD::PSHUFD: 2762 case X86ISD::PSHUFHW: 2763 case X86ISD::PSHUFLW: 2764 case X86ISD::SHUFPD: 2765 case X86ISD::PALIGN: 2766 case X86ISD::SHUFPS: 2767 case X86ISD::MOVLHPS: 2768 case X86ISD::MOVLHPD: 2769 case X86ISD::MOVHLPS: 2770 case X86ISD::MOVLPS: 2771 case X86ISD::MOVLPD: 2772 case X86ISD::MOVSHDUP: 2773 case X86ISD::MOVSLDUP: 2774 case X86ISD::MOVDDUP: 2775 case X86ISD::MOVSS: 2776 case X86ISD::MOVSD: 2777 case X86ISD::UNPCKLPS: 2778 case X86ISD::UNPCKLPD: 2779 case X86ISD::VUNPCKLPSY: 2780 case X86ISD::VUNPCKLPDY: 2781 case X86ISD::PUNPCKLWD: 2782 case X86ISD::PUNPCKLBW: 2783 case X86ISD::PUNPCKLDQ: 2784 case X86ISD::PUNPCKLQDQ: 2785 case X86ISD::UNPCKHPS: 2786 case X86ISD::UNPCKHPD: 2787 case X86ISD::VUNPCKHPSY: 2788 case X86ISD::VUNPCKHPDY: 2789 case X86ISD::PUNPCKHWD: 2790 case X86ISD::PUNPCKHBW: 2791 case X86ISD::PUNPCKHDQ: 2792 case X86ISD::PUNPCKHQDQ: 2793 case X86ISD::VPERMILPS: 2794 case X86ISD::VPERMILPSY: 2795 case X86ISD::VPERMILPD: 2796 case X86ISD::VPERMILPDY: 2797 case X86ISD::VPERM2F128: 2798 return true; 2799 } 2800 return false; 2801} 2802 2803static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2804 SDValue V1, SelectionDAG &DAG) { 2805 switch(Opc) { 2806 default: llvm_unreachable("Unknown x86 shuffle node"); 2807 case X86ISD::MOVSHDUP: 2808 case X86ISD::MOVSLDUP: 2809 case X86ISD::MOVDDUP: 2810 return DAG.getNode(Opc, dl, VT, V1); 2811 } 2812 2813 return SDValue(); 2814} 2815 2816static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2817 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) { 2818 switch(Opc) { 2819 default: llvm_unreachable("Unknown x86 shuffle node"); 2820 case X86ISD::PSHUFD: 2821 case X86ISD::PSHUFHW: 2822 case X86ISD::PSHUFLW: 2823 case X86ISD::VPERMILPS: 2824 case X86ISD::VPERMILPSY: 2825 case X86ISD::VPERMILPD: 2826 case X86ISD::VPERMILPDY: 2827 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8)); 2828 } 2829 2830 return SDValue(); 2831} 2832 2833static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2834 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) { 2835 switch(Opc) { 2836 default: llvm_unreachable("Unknown x86 shuffle node"); 2837 case X86ISD::PALIGN: 2838 case X86ISD::SHUFPD: 2839 case X86ISD::SHUFPS: 2840 case X86ISD::VPERM2F128: 2841 return DAG.getNode(Opc, dl, VT, V1, V2, 2842 DAG.getConstant(TargetMask, MVT::i8)); 2843 } 2844 return SDValue(); 2845} 2846 2847static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2848 SDValue V1, SDValue V2, SelectionDAG &DAG) { 2849 switch(Opc) { 2850 default: llvm_unreachable("Unknown x86 shuffle node"); 2851 case X86ISD::MOVLHPS: 2852 case X86ISD::MOVLHPD: 2853 case X86ISD::MOVHLPS: 2854 case X86ISD::MOVLPS: 2855 case X86ISD::MOVLPD: 2856 case X86ISD::MOVSS: 2857 case X86ISD::MOVSD: 2858 case X86ISD::UNPCKLPS: 2859 case X86ISD::UNPCKLPD: 2860 case X86ISD::VUNPCKLPSY: 2861 case X86ISD::VUNPCKLPDY: 2862 case X86ISD::PUNPCKLWD: 2863 case X86ISD::PUNPCKLBW: 2864 case X86ISD::PUNPCKLDQ: 2865 case X86ISD::PUNPCKLQDQ: 2866 case X86ISD::UNPCKHPS: 2867 case X86ISD::UNPCKHPD: 2868 case X86ISD::VUNPCKHPSY: 2869 case X86ISD::VUNPCKHPDY: 2870 case X86ISD::PUNPCKHWD: 2871 case X86ISD::PUNPCKHBW: 2872 case X86ISD::PUNPCKHDQ: 2873 case X86ISD::PUNPCKHQDQ: 2874 return DAG.getNode(Opc, dl, VT, V1, V2); 2875 } 2876 return SDValue(); 2877} 2878 2879SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { 2880 MachineFunction &MF = DAG.getMachineFunction(); 2881 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2882 int ReturnAddrIndex = FuncInfo->getRAIndex(); 2883 2884 if (ReturnAddrIndex == 0) { 2885 // Set up a frame object for the return address. 2886 uint64_t SlotSize = TD->getPointerSize(); 2887 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize, 2888 false); 2889 FuncInfo->setRAIndex(ReturnAddrIndex); 2890 } 2891 2892 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); 2893} 2894 2895 2896bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, 2897 bool hasSymbolicDisplacement) { 2898 // Offset should fit into 32 bit immediate field. 2899 if (!isInt<32>(Offset)) 2900 return false; 2901 2902 // If we don't have a symbolic displacement - we don't have any extra 2903 // restrictions. 2904 if (!hasSymbolicDisplacement) 2905 return true; 2906 2907 // FIXME: Some tweaks might be needed for medium code model. 2908 if (M != CodeModel::Small && M != CodeModel::Kernel) 2909 return false; 2910 2911 // For small code model we assume that latest object is 16MB before end of 31 2912 // bits boundary. We may also accept pretty large negative constants knowing 2913 // that all objects are in the positive half of address space. 2914 if (M == CodeModel::Small && Offset < 16*1024*1024) 2915 return true; 2916 2917 // For kernel code model we know that all object resist in the negative half 2918 // of 32bits address space. We may not accept negative offsets, since they may 2919 // be just off and we may accept pretty large positive ones. 2920 if (M == CodeModel::Kernel && Offset > 0) 2921 return true; 2922 2923 return false; 2924} 2925 2926/// isCalleePop - Determines whether the callee is required to pop its 2927/// own arguments. Callee pop is necessary to support tail calls. 2928bool X86::isCalleePop(CallingConv::ID CallingConv, 2929 bool is64Bit, bool IsVarArg, bool TailCallOpt) { 2930 if (IsVarArg) 2931 return false; 2932 2933 switch (CallingConv) { 2934 default: 2935 return false; 2936 case CallingConv::X86_StdCall: 2937 return !is64Bit; 2938 case CallingConv::X86_FastCall: 2939 return !is64Bit; 2940 case CallingConv::X86_ThisCall: 2941 return !is64Bit; 2942 case CallingConv::Fast: 2943 return TailCallOpt; 2944 case CallingConv::GHC: 2945 return TailCallOpt; 2946 } 2947} 2948 2949/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86 2950/// specific condition code, returning the condition code and the LHS/RHS of the 2951/// comparison to make. 2952static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP, 2953 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) { 2954 if (!isFP) { 2955 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 2956 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) { 2957 // X > -1 -> X == 0, jump !sign. 2958 RHS = DAG.getConstant(0, RHS.getValueType()); 2959 return X86::COND_NS; 2960 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) { 2961 // X < 0 -> X == 0, jump on sign. 2962 return X86::COND_S; 2963 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) { 2964 // X < 1 -> X <= 0 2965 RHS = DAG.getConstant(0, RHS.getValueType()); 2966 return X86::COND_LE; 2967 } 2968 } 2969 2970 switch (SetCCOpcode) { 2971 default: llvm_unreachable("Invalid integer condition!"); 2972 case ISD::SETEQ: return X86::COND_E; 2973 case ISD::SETGT: return X86::COND_G; 2974 case ISD::SETGE: return X86::COND_GE; 2975 case ISD::SETLT: return X86::COND_L; 2976 case ISD::SETLE: return X86::COND_LE; 2977 case ISD::SETNE: return X86::COND_NE; 2978 case ISD::SETULT: return X86::COND_B; 2979 case ISD::SETUGT: return X86::COND_A; 2980 case ISD::SETULE: return X86::COND_BE; 2981 case ISD::SETUGE: return X86::COND_AE; 2982 } 2983 } 2984 2985 // First determine if it is required or is profitable to flip the operands. 2986 2987 // If LHS is a foldable load, but RHS is not, flip the condition. 2988 if (ISD::isNON_EXTLoad(LHS.getNode()) && 2989 !ISD::isNON_EXTLoad(RHS.getNode())) { 2990 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode); 2991 std::swap(LHS, RHS); 2992 } 2993 2994 switch (SetCCOpcode) { 2995 default: break; 2996 case ISD::SETOLT: 2997 case ISD::SETOLE: 2998 case ISD::SETUGT: 2999 case ISD::SETUGE: 3000 std::swap(LHS, RHS); 3001 break; 3002 } 3003 3004 // On a floating point condition, the flags are set as follows: 3005 // ZF PF CF op 3006 // 0 | 0 | 0 | X > Y 3007 // 0 | 0 | 1 | X < Y 3008 // 1 | 0 | 0 | X == Y 3009 // 1 | 1 | 1 | unordered 3010 switch (SetCCOpcode) { 3011 default: llvm_unreachable("Condcode should be pre-legalized away"); 3012 case ISD::SETUEQ: 3013 case ISD::SETEQ: return X86::COND_E; 3014 case ISD::SETOLT: // flipped 3015 case ISD::SETOGT: 3016 case ISD::SETGT: return X86::COND_A; 3017 case ISD::SETOLE: // flipped 3018 case ISD::SETOGE: 3019 case ISD::SETGE: return X86::COND_AE; 3020 case ISD::SETUGT: // flipped 3021 case ISD::SETULT: 3022 case ISD::SETLT: return X86::COND_B; 3023 case ISD::SETUGE: // flipped 3024 case ISD::SETULE: 3025 case ISD::SETLE: return X86::COND_BE; 3026 case ISD::SETONE: 3027 case ISD::SETNE: return X86::COND_NE; 3028 case ISD::SETUO: return X86::COND_P; 3029 case ISD::SETO: return X86::COND_NP; 3030 case ISD::SETOEQ: 3031 case ISD::SETUNE: return X86::COND_INVALID; 3032 } 3033} 3034 3035/// hasFPCMov - is there a floating point cmov for the specific X86 condition 3036/// code. Current x86 isa includes the following FP cmov instructions: 3037/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu. 3038static bool hasFPCMov(unsigned X86CC) { 3039 switch (X86CC) { 3040 default: 3041 return false; 3042 case X86::COND_B: 3043 case X86::COND_BE: 3044 case X86::COND_E: 3045 case X86::COND_P: 3046 case X86::COND_A: 3047 case X86::COND_AE: 3048 case X86::COND_NE: 3049 case X86::COND_NP: 3050 return true; 3051 } 3052} 3053 3054/// isFPImmLegal - Returns true if the target can instruction select the 3055/// specified FP immediate natively. If false, the legalizer will 3056/// materialize the FP immediate as a load from a constant pool. 3057bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 3058 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) { 3059 if (Imm.bitwiseIsEqual(LegalFPImmediates[i])) 3060 return true; 3061 } 3062 return false; 3063} 3064 3065/// isUndefOrInRange - Return true if Val is undef or if its value falls within 3066/// the specified range (L, H]. 3067static bool isUndefOrInRange(int Val, int Low, int Hi) { 3068 return (Val < 0) || (Val >= Low && Val < Hi); 3069} 3070 3071/// isUndefOrInRange - Return true if every element in Mask, begining 3072/// from position Pos and ending in Pos+Size, falls within the specified 3073/// range (L, L+Pos]. or is undef. 3074static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask, 3075 int Pos, int Size, int Low, int Hi) { 3076 for (int i = Pos, e = Pos+Size; i != e; ++i) 3077 if (!isUndefOrInRange(Mask[i], Low, Hi)) 3078 return false; 3079 return true; 3080} 3081 3082/// isUndefOrEqual - Val is either less than zero (undef) or equal to the 3083/// specified value. 3084static bool isUndefOrEqual(int Val, int CmpVal) { 3085 if (Val < 0 || Val == CmpVal) 3086 return true; 3087 return false; 3088} 3089 3090/// isSequentialOrUndefInRange - Return true if every element in Mask, begining 3091/// from position Pos and ending in Pos+Size, falls within the specified 3092/// sequential range (L, L+Pos]. or is undef. 3093static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask, 3094 int Pos, int Size, int Low) { 3095 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low) 3096 if (!isUndefOrEqual(Mask[i], Low)) 3097 return false; 3098 return true; 3099} 3100 3101/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that 3102/// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference 3103/// the second operand. 3104static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3105 if (VT == MVT::v4f32 || VT == MVT::v4i32 ) 3106 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4); 3107 if (VT == MVT::v2f64 || VT == MVT::v2i64) 3108 return (Mask[0] < 2 && Mask[1] < 2); 3109 return false; 3110} 3111 3112bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) { 3113 SmallVector<int, 8> M; 3114 N->getMask(M); 3115 return ::isPSHUFDMask(M, N->getValueType(0)); 3116} 3117 3118/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that 3119/// is suitable for input to PSHUFHW. 3120static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3121 if (VT != MVT::v8i16) 3122 return false; 3123 3124 // Lower quadword copied in order or undef. 3125 for (int i = 0; i != 4; ++i) 3126 if (Mask[i] >= 0 && Mask[i] != i) 3127 return false; 3128 3129 // Upper quadword shuffled. 3130 for (int i = 4; i != 8; ++i) 3131 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7)) 3132 return false; 3133 3134 return true; 3135} 3136 3137bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) { 3138 SmallVector<int, 8> M; 3139 N->getMask(M); 3140 return ::isPSHUFHWMask(M, N->getValueType(0)); 3141} 3142 3143/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that 3144/// is suitable for input to PSHUFLW. 3145static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3146 if (VT != MVT::v8i16) 3147 return false; 3148 3149 // Upper quadword copied in order. 3150 for (int i = 4; i != 8; ++i) 3151 if (Mask[i] >= 0 && Mask[i] != i) 3152 return false; 3153 3154 // Lower quadword shuffled. 3155 for (int i = 0; i != 4; ++i) 3156 if (Mask[i] >= 4) 3157 return false; 3158 3159 return true; 3160} 3161 3162bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) { 3163 SmallVector<int, 8> M; 3164 N->getMask(M); 3165 return ::isPSHUFLWMask(M, N->getValueType(0)); 3166} 3167 3168/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that 3169/// is suitable for input to PALIGNR. 3170static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT, 3171 bool hasSSSE3) { 3172 int i, e = VT.getVectorNumElements(); 3173 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64) 3174 return false; 3175 3176 // Do not handle v2i64 / v2f64 shuffles with palignr. 3177 if (e < 4 || !hasSSSE3) 3178 return false; 3179 3180 for (i = 0; i != e; ++i) 3181 if (Mask[i] >= 0) 3182 break; 3183 3184 // All undef, not a palignr. 3185 if (i == e) 3186 return false; 3187 3188 // Make sure we're shifting in the right direction. 3189 if (Mask[i] <= i) 3190 return false; 3191 3192 int s = Mask[i] - i; 3193 3194 // Check the rest of the elements to see if they are consecutive. 3195 for (++i; i != e; ++i) { 3196 int m = Mask[i]; 3197 if (m >= 0 && m != s+i) 3198 return false; 3199 } 3200 return true; 3201} 3202 3203/// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand 3204/// specifies a shuffle of elements that is suitable for input to 256-bit 3205/// VSHUFPSY. 3206static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT, 3207 const X86Subtarget *Subtarget) { 3208 int NumElems = VT.getVectorNumElements(); 3209 3210 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256) 3211 return false; 3212 3213 if (NumElems != 8) 3214 return false; 3215 3216 // VSHUFPSY divides the resulting vector into 4 chunks. 3217 // The sources are also splitted into 4 chunks, and each destination 3218 // chunk must come from a different source chunk. 3219 // 3220 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0 3221 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9 3222 // 3223 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4, 3224 // Y3..Y0, Y3..Y0, X3..X0, X3..X0 3225 // 3226 int QuarterSize = NumElems/4; 3227 int HalfSize = QuarterSize*2; 3228 for (int i = 0; i < QuarterSize; ++i) 3229 if (!isUndefOrInRange(Mask[i], 0, HalfSize)) 3230 return false; 3231 for (int i = QuarterSize; i < QuarterSize*2; ++i) 3232 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize)) 3233 return false; 3234 3235 // The mask of the second half must be the same as the first but with 3236 // the appropriate offsets. This works in the same way as VPERMILPS 3237 // works with masks. 3238 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) { 3239 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems)) 3240 return false; 3241 int FstHalfIdx = i-HalfSize; 3242 if (Mask[FstHalfIdx] < 0) 3243 continue; 3244 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize)) 3245 return false; 3246 } 3247 for (int i = QuarterSize*3; i < NumElems; ++i) { 3248 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2)) 3249 return false; 3250 int FstHalfIdx = i-HalfSize; 3251 if (Mask[FstHalfIdx] < 0) 3252 continue; 3253 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize)) 3254 return false; 3255 3256 } 3257 3258 return true; 3259} 3260 3261/// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle 3262/// the specified VECTOR_MASK mask with VSHUFPSY instruction. 3263static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) { 3264 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3265 EVT VT = SVOp->getValueType(0); 3266 int NumElems = VT.getVectorNumElements(); 3267 3268 assert(NumElems == 8 && VT.getSizeInBits() == 256 && 3269 "Only supports v8i32 and v8f32 types"); 3270 3271 int HalfSize = NumElems/2; 3272 unsigned Mask = 0; 3273 for (int i = 0; i != NumElems ; ++i) { 3274 if (SVOp->getMaskElt(i) < 0) 3275 continue; 3276 // The mask of the first half must be equal to the second one. 3277 unsigned Shamt = (i%HalfSize)*2; 3278 unsigned Elt = SVOp->getMaskElt(i) % HalfSize; 3279 Mask |= Elt << Shamt; 3280 } 3281 3282 return Mask; 3283} 3284 3285/// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand 3286/// specifies a shuffle of elements that is suitable for input to 256-bit 3287/// VSHUFPDY. This shuffle doesn't have the same restriction as the PS 3288/// version and the mask of the second half isn't binded with the first 3289/// one. 3290static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT, 3291 const X86Subtarget *Subtarget) { 3292 int NumElems = VT.getVectorNumElements(); 3293 3294 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256) 3295 return false; 3296 3297 if (NumElems != 4) 3298 return false; 3299 3300 // VSHUFPSY divides the resulting vector into 4 chunks. 3301 // The sources are also splitted into 4 chunks, and each destination 3302 // chunk must come from a different source chunk. 3303 // 3304 // SRC1 => X3 X2 X1 X0 3305 // SRC2 => Y3 Y2 Y1 Y0 3306 // 3307 // DST => Y2..Y3, X2..X3, Y1..Y0, X1..X0 3308 // 3309 int QuarterSize = NumElems/4; 3310 int HalfSize = QuarterSize*2; 3311 for (int i = 0; i < QuarterSize; ++i) 3312 if (!isUndefOrInRange(Mask[i], 0, HalfSize)) 3313 return false; 3314 for (int i = QuarterSize; i < QuarterSize*2; ++i) 3315 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize)) 3316 return false; 3317 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) 3318 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems)) 3319 return false; 3320 for (int i = QuarterSize*3; i < NumElems; ++i) 3321 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2)) 3322 return false; 3323 3324 return true; 3325} 3326 3327/// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle 3328/// the specified VECTOR_MASK mask with VSHUFPDY instruction. 3329static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) { 3330 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3331 EVT VT = SVOp->getValueType(0); 3332 int NumElems = VT.getVectorNumElements(); 3333 3334 assert(NumElems == 4 && VT.getSizeInBits() == 256 && 3335 "Only supports v4i64 and v4f64 types"); 3336 3337 int HalfSize = NumElems/2; 3338 unsigned Mask = 0; 3339 for (int i = 0; i != NumElems ; ++i) { 3340 if (SVOp->getMaskElt(i) < 0) 3341 continue; 3342 int Elt = SVOp->getMaskElt(i) % HalfSize; 3343 Mask |= Elt << i; 3344 } 3345 3346 return Mask; 3347} 3348 3349/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand 3350/// specifies a shuffle of elements that is suitable for input to 128-bit 3351/// SHUFPS and SHUFPD. 3352static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3353 int NumElems = VT.getVectorNumElements(); 3354 3355 if (VT.getSizeInBits() != 128) 3356 return false; 3357 3358 if (NumElems != 2 && NumElems != 4) 3359 return false; 3360 3361 int Half = NumElems / 2; 3362 for (int i = 0; i < Half; ++i) 3363 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3364 return false; 3365 for (int i = Half; i < NumElems; ++i) 3366 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3367 return false; 3368 3369 return true; 3370} 3371 3372bool X86::isSHUFPMask(ShuffleVectorSDNode *N) { 3373 SmallVector<int, 8> M; 3374 N->getMask(M); 3375 return ::isSHUFPMask(M, N->getValueType(0)); 3376} 3377 3378/// isCommutedSHUFP - Returns true if the shuffle mask is exactly 3379/// the reverse of what x86 shuffles want. x86 shuffles requires the lower 3380/// half elements to come from vector 1 (which would equal the dest.) and 3381/// the upper half to come from vector 2. 3382static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3383 int NumElems = VT.getVectorNumElements(); 3384 3385 if (NumElems != 2 && NumElems != 4) 3386 return false; 3387 3388 int Half = NumElems / 2; 3389 for (int i = 0; i < Half; ++i) 3390 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3391 return false; 3392 for (int i = Half; i < NumElems; ++i) 3393 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3394 return false; 3395 return true; 3396} 3397 3398static bool isCommutedSHUFP(ShuffleVectorSDNode *N) { 3399 SmallVector<int, 8> M; 3400 N->getMask(M); 3401 return isCommutedSHUFPMask(M, N->getValueType(0)); 3402} 3403 3404/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand 3405/// specifies a shuffle of elements that is suitable for input to MOVHLPS. 3406bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) { 3407 EVT VT = N->getValueType(0); 3408 unsigned NumElems = VT.getVectorNumElements(); 3409 3410 if (VT.getSizeInBits() != 128) 3411 return false; 3412 3413 if (NumElems != 4) 3414 return false; 3415 3416 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3 3417 return isUndefOrEqual(N->getMaskElt(0), 6) && 3418 isUndefOrEqual(N->getMaskElt(1), 7) && 3419 isUndefOrEqual(N->getMaskElt(2), 2) && 3420 isUndefOrEqual(N->getMaskElt(3), 3); 3421} 3422 3423/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form 3424/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef, 3425/// <2, 3, 2, 3> 3426bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) { 3427 EVT VT = N->getValueType(0); 3428 unsigned NumElems = VT.getVectorNumElements(); 3429 3430 if (VT.getSizeInBits() != 128) 3431 return false; 3432 3433 if (NumElems != 4) 3434 return false; 3435 3436 return isUndefOrEqual(N->getMaskElt(0), 2) && 3437 isUndefOrEqual(N->getMaskElt(1), 3) && 3438 isUndefOrEqual(N->getMaskElt(2), 2) && 3439 isUndefOrEqual(N->getMaskElt(3), 3); 3440} 3441 3442/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand 3443/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}. 3444bool X86::isMOVLPMask(ShuffleVectorSDNode *N) { 3445 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3446 3447 if (NumElems != 2 && NumElems != 4) 3448 return false; 3449 3450 for (unsigned i = 0; i < NumElems/2; ++i) 3451 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems)) 3452 return false; 3453 3454 for (unsigned i = NumElems/2; i < NumElems; ++i) 3455 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3456 return false; 3457 3458 return true; 3459} 3460 3461/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand 3462/// specifies a shuffle of elements that is suitable for input to MOVLHPS. 3463bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) { 3464 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3465 3466 if ((NumElems != 2 && NumElems != 4) 3467 || N->getValueType(0).getSizeInBits() > 128) 3468 return false; 3469 3470 for (unsigned i = 0; i < NumElems/2; ++i) 3471 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3472 return false; 3473 3474 for (unsigned i = 0; i < NumElems/2; ++i) 3475 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems)) 3476 return false; 3477 3478 return true; 3479} 3480 3481/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand 3482/// specifies a shuffle of elements that is suitable for input to UNPCKL. 3483static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3484 bool V2IsSplat = false) { 3485 int NumElts = VT.getVectorNumElements(); 3486 3487 assert((VT.is128BitVector() || VT.is256BitVector()) && 3488 "Unsupported vector type for unpckh"); 3489 3490 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8) 3491 return false; 3492 3493 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3494 // independently on 128-bit lanes. 3495 unsigned NumLanes = VT.getSizeInBits()/128; 3496 unsigned NumLaneElts = NumElts/NumLanes; 3497 3498 unsigned Start = 0; 3499 unsigned End = NumLaneElts; 3500 for (unsigned s = 0; s < NumLanes; ++s) { 3501 for (unsigned i = Start, j = s * NumLaneElts; 3502 i != End; 3503 i += 2, ++j) { 3504 int BitI = Mask[i]; 3505 int BitI1 = Mask[i+1]; 3506 if (!isUndefOrEqual(BitI, j)) 3507 return false; 3508 if (V2IsSplat) { 3509 if (!isUndefOrEqual(BitI1, NumElts)) 3510 return false; 3511 } else { 3512 if (!isUndefOrEqual(BitI1, j + NumElts)) 3513 return false; 3514 } 3515 } 3516 // Process the next 128 bits. 3517 Start += NumLaneElts; 3518 End += NumLaneElts; 3519 } 3520 3521 return true; 3522} 3523 3524bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) { 3525 SmallVector<int, 8> M; 3526 N->getMask(M); 3527 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat); 3528} 3529 3530/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand 3531/// specifies a shuffle of elements that is suitable for input to UNPCKH. 3532static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT, 3533 bool V2IsSplat = false) { 3534 int NumElts = VT.getVectorNumElements(); 3535 3536 assert((VT.is128BitVector() || VT.is256BitVector()) && 3537 "Unsupported vector type for unpckh"); 3538 3539 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8) 3540 return false; 3541 3542 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3543 // independently on 128-bit lanes. 3544 unsigned NumLanes = VT.getSizeInBits()/128; 3545 unsigned NumLaneElts = NumElts/NumLanes; 3546 3547 unsigned Start = 0; 3548 unsigned End = NumLaneElts; 3549 for (unsigned l = 0; l != NumLanes; ++l) { 3550 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2; 3551 i != End; i += 2, ++j) { 3552 int BitI = Mask[i]; 3553 int BitI1 = Mask[i+1]; 3554 if (!isUndefOrEqual(BitI, j)) 3555 return false; 3556 if (V2IsSplat) { 3557 if (isUndefOrEqual(BitI1, NumElts)) 3558 return false; 3559 } else { 3560 if (!isUndefOrEqual(BitI1, j+NumElts)) 3561 return false; 3562 } 3563 } 3564 // Process the next 128 bits. 3565 Start += NumLaneElts; 3566 End += NumLaneElts; 3567 } 3568 return true; 3569} 3570 3571bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) { 3572 SmallVector<int, 8> M; 3573 N->getMask(M); 3574 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat); 3575} 3576 3577/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form 3578/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef, 3579/// <0, 0, 1, 1> 3580static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3581 int NumElems = VT.getVectorNumElements(); 3582 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3583 return false; 3584 3585 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern 3586 // FIXME: Need a better way to get rid of this, there's no latency difference 3587 // between UNPCKLPD and MOVDDUP, the later should always be checked first and 3588 // the former later. We should also remove the "_undef" special mask. 3589 if (NumElems == 4 && VT.getSizeInBits() == 256) 3590 return false; 3591 3592 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3593 // independently on 128-bit lanes. 3594 unsigned NumLanes = VT.getSizeInBits() / 128; 3595 unsigned NumLaneElts = NumElems / NumLanes; 3596 3597 for (unsigned s = 0; s < NumLanes; ++s) { 3598 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts; 3599 i != NumLaneElts * (s + 1); 3600 i += 2, ++j) { 3601 int BitI = Mask[i]; 3602 int BitI1 = Mask[i+1]; 3603 3604 if (!isUndefOrEqual(BitI, j)) 3605 return false; 3606 if (!isUndefOrEqual(BitI1, j)) 3607 return false; 3608 } 3609 } 3610 3611 return true; 3612} 3613 3614bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) { 3615 SmallVector<int, 8> M; 3616 N->getMask(M); 3617 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0)); 3618} 3619 3620/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form 3621/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef, 3622/// <2, 2, 3, 3> 3623static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3624 int NumElems = VT.getVectorNumElements(); 3625 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3626 return false; 3627 3628 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) { 3629 int BitI = Mask[i]; 3630 int BitI1 = Mask[i+1]; 3631 if (!isUndefOrEqual(BitI, j)) 3632 return false; 3633 if (!isUndefOrEqual(BitI1, j)) 3634 return false; 3635 } 3636 return true; 3637} 3638 3639bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) { 3640 SmallVector<int, 8> M; 3641 N->getMask(M); 3642 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0)); 3643} 3644 3645/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand 3646/// specifies a shuffle of elements that is suitable for input to MOVSS, 3647/// MOVSD, and MOVD, i.e. setting the lowest element. 3648static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3649 if (VT.getVectorElementType().getSizeInBits() < 32) 3650 return false; 3651 3652 int NumElts = VT.getVectorNumElements(); 3653 3654 if (!isUndefOrEqual(Mask[0], NumElts)) 3655 return false; 3656 3657 for (int i = 1; i < NumElts; ++i) 3658 if (!isUndefOrEqual(Mask[i], i)) 3659 return false; 3660 3661 return true; 3662} 3663 3664bool X86::isMOVLMask(ShuffleVectorSDNode *N) { 3665 SmallVector<int, 8> M; 3666 N->getMask(M); 3667 return ::isMOVLMask(M, N->getValueType(0)); 3668} 3669 3670/// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered 3671/// as permutations between 128-bit chunks or halves. As an example: this 3672/// shuffle bellow: 3673/// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15> 3674/// The first half comes from the second half of V1 and the second half from the 3675/// the second half of V2. 3676static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT, 3677 const X86Subtarget *Subtarget) { 3678 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256) 3679 return false; 3680 3681 // The shuffle result is divided into half A and half B. In total the two 3682 // sources have 4 halves, namely: C, D, E, F. The final values of A and 3683 // B must come from C, D, E or F. 3684 int HalfSize = VT.getVectorNumElements()/2; 3685 bool MatchA = false, MatchB = false; 3686 3687 // Check if A comes from one of C, D, E, F. 3688 for (int Half = 0; Half < 4; ++Half) { 3689 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) { 3690 MatchA = true; 3691 break; 3692 } 3693 } 3694 3695 // Check if B comes from one of C, D, E, F. 3696 for (int Half = 0; Half < 4; ++Half) { 3697 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) { 3698 MatchB = true; 3699 break; 3700 } 3701 } 3702 3703 return MatchA && MatchB; 3704} 3705 3706/// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle 3707/// the specified VECTOR_MASK mask with VPERM2F128 instructions. 3708static unsigned getShuffleVPERM2F128Immediate(SDNode *N) { 3709 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3710 EVT VT = SVOp->getValueType(0); 3711 3712 int HalfSize = VT.getVectorNumElements()/2; 3713 3714 int FstHalf = 0, SndHalf = 0; 3715 for (int i = 0; i < HalfSize; ++i) { 3716 if (SVOp->getMaskElt(i) > 0) { 3717 FstHalf = SVOp->getMaskElt(i)/HalfSize; 3718 break; 3719 } 3720 } 3721 for (int i = HalfSize; i < HalfSize*2; ++i) { 3722 if (SVOp->getMaskElt(i) > 0) { 3723 SndHalf = SVOp->getMaskElt(i)/HalfSize; 3724 break; 3725 } 3726 } 3727 3728 return (FstHalf | (SndHalf << 4)); 3729} 3730 3731/// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand 3732/// specifies a shuffle of elements that is suitable for input to VPERMILPD*. 3733/// Note that VPERMIL mask matching is different depending whether theunderlying 3734/// type is 32 or 64. In the VPERMILPS the high half of the mask should point 3735/// to the same elements of the low, but to the higher half of the source. 3736/// In VPERMILPD the two lanes could be shuffled independently of each other 3737/// with the same restriction that lanes can't be crossed. 3738static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT, 3739 const X86Subtarget *Subtarget) { 3740 int NumElts = VT.getVectorNumElements(); 3741 int NumLanes = VT.getSizeInBits()/128; 3742 3743 if (!Subtarget->hasAVX()) 3744 return false; 3745 3746 // Match any permutation of 128-bit vector with 64-bit types 3747 if (NumLanes == 1 && NumElts != 2) 3748 return false; 3749 3750 // Only match 256-bit with 32 types 3751 if (VT.getSizeInBits() == 256 && NumElts != 4) 3752 return false; 3753 3754 // The mask on the high lane is independent of the low. Both can match 3755 // any element in inside its own lane, but can't cross. 3756 int LaneSize = NumElts/NumLanes; 3757 for (int l = 0; l < NumLanes; ++l) 3758 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) { 3759 int LaneStart = l*LaneSize; 3760 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize)) 3761 return false; 3762 } 3763 3764 return true; 3765} 3766 3767/// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand 3768/// specifies a shuffle of elements that is suitable for input to VPERMILPS*. 3769/// Note that VPERMIL mask matching is different depending whether theunderlying 3770/// type is 32 or 64. In the VPERMILPS the high half of the mask should point 3771/// to the same elements of the low, but to the higher half of the source. 3772/// In VPERMILPD the two lanes could be shuffled independently of each other 3773/// with the same restriction that lanes can't be crossed. 3774static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT, 3775 const X86Subtarget *Subtarget) { 3776 unsigned NumElts = VT.getVectorNumElements(); 3777 unsigned NumLanes = VT.getSizeInBits()/128; 3778 3779 if (!Subtarget->hasAVX()) 3780 return false; 3781 3782 // Match any permutation of 128-bit vector with 32-bit types 3783 if (NumLanes == 1 && NumElts != 4) 3784 return false; 3785 3786 // Only match 256-bit with 32 types 3787 if (VT.getSizeInBits() == 256 && NumElts != 8) 3788 return false; 3789 3790 // The mask on the high lane should be the same as the low. Actually, 3791 // they can differ if any of the corresponding index in a lane is undef 3792 // and the other stays in range. 3793 int LaneSize = NumElts/NumLanes; 3794 for (int i = 0; i < LaneSize; ++i) { 3795 int HighElt = i+LaneSize; 3796 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts); 3797 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize); 3798 3799 if (!HighValid || !LowValid) 3800 return false; 3801 if (Mask[i] < 0 || Mask[HighElt] < 0) 3802 continue; 3803 if (Mask[HighElt]-Mask[i] != LaneSize) 3804 return false; 3805 } 3806 3807 return true; 3808} 3809 3810/// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle 3811/// the specified VECTOR_MASK mask with VPERMILPS* instructions. 3812static unsigned getShuffleVPERMILPSImmediate(SDNode *N) { 3813 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3814 EVT VT = SVOp->getValueType(0); 3815 3816 int NumElts = VT.getVectorNumElements(); 3817 int NumLanes = VT.getSizeInBits()/128; 3818 int LaneSize = NumElts/NumLanes; 3819 3820 // Although the mask is equal for both lanes do it twice to get the cases 3821 // where a mask will match because the same mask element is undef on the 3822 // first half but valid on the second. This would get pathological cases 3823 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid. 3824 unsigned Mask = 0; 3825 for (int l = 0; l < NumLanes; ++l) { 3826 for (int i = 0; i < LaneSize; ++i) { 3827 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize)); 3828 if (MaskElt < 0) 3829 continue; 3830 if (MaskElt >= LaneSize) 3831 MaskElt -= LaneSize; 3832 Mask |= MaskElt << (i*2); 3833 } 3834 } 3835 3836 return Mask; 3837} 3838 3839/// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle 3840/// the specified VECTOR_MASK mask with VPERMILPD* instructions. 3841static unsigned getShuffleVPERMILPDImmediate(SDNode *N) { 3842 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3843 EVT VT = SVOp->getValueType(0); 3844 3845 int NumElts = VT.getVectorNumElements(); 3846 int NumLanes = VT.getSizeInBits()/128; 3847 3848 unsigned Mask = 0; 3849 int LaneSize = NumElts/NumLanes; 3850 for (int l = 0; l < NumLanes; ++l) 3851 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) { 3852 int MaskElt = SVOp->getMaskElt(i); 3853 if (MaskElt < 0) 3854 continue; 3855 Mask |= (MaskElt-l*LaneSize) << i; 3856 } 3857 3858 return Mask; 3859} 3860 3861/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse 3862/// of what x86 movss want. X86 movs requires the lowest element to be lowest 3863/// element of vector 2 and the other elements to come from vector 1 in order. 3864static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3865 bool V2IsSplat = false, bool V2IsUndef = false) { 3866 int NumOps = VT.getVectorNumElements(); 3867 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16) 3868 return false; 3869 3870 if (!isUndefOrEqual(Mask[0], 0)) 3871 return false; 3872 3873 for (int i = 1; i < NumOps; ++i) 3874 if (!(isUndefOrEqual(Mask[i], i+NumOps) || 3875 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) || 3876 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps)))) 3877 return false; 3878 3879 return true; 3880} 3881 3882static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false, 3883 bool V2IsUndef = false) { 3884 SmallVector<int, 8> M; 3885 N->getMask(M); 3886 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef); 3887} 3888 3889/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3890/// specifies a shuffle of elements that is suitable for input to MOVSHDUP. 3891/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7> 3892bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N, 3893 const X86Subtarget *Subtarget) { 3894 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX()) 3895 return false; 3896 3897 // The second vector must be undef 3898 if (N->getOperand(1).getOpcode() != ISD::UNDEF) 3899 return false; 3900 3901 EVT VT = N->getValueType(0); 3902 unsigned NumElems = VT.getVectorNumElements(); 3903 3904 if ((VT.getSizeInBits() == 128 && NumElems != 4) || 3905 (VT.getSizeInBits() == 256 && NumElems != 8)) 3906 return false; 3907 3908 // "i+1" is the value the indexed mask element must have 3909 for (unsigned i = 0; i < NumElems; i += 2) 3910 if (!isUndefOrEqual(N->getMaskElt(i), i+1) || 3911 !isUndefOrEqual(N->getMaskElt(i+1), i+1)) 3912 return false; 3913 3914 return true; 3915} 3916 3917/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3918/// specifies a shuffle of elements that is suitable for input to MOVSLDUP. 3919/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6> 3920bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N, 3921 const X86Subtarget *Subtarget) { 3922 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX()) 3923 return false; 3924 3925 // The second vector must be undef 3926 if (N->getOperand(1).getOpcode() != ISD::UNDEF) 3927 return false; 3928 3929 EVT VT = N->getValueType(0); 3930 unsigned NumElems = VT.getVectorNumElements(); 3931 3932 if ((VT.getSizeInBits() == 128 && NumElems != 4) || 3933 (VT.getSizeInBits() == 256 && NumElems != 8)) 3934 return false; 3935 3936 // "i" is the value the indexed mask element must have 3937 for (unsigned i = 0; i < NumElems; i += 2) 3938 if (!isUndefOrEqual(N->getMaskElt(i), i) || 3939 !isUndefOrEqual(N->getMaskElt(i+1), i)) 3940 return false; 3941 3942 return true; 3943} 3944 3945/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand 3946/// specifies a shuffle of elements that is suitable for input to 256-bit 3947/// version of MOVDDUP. 3948static bool isMOVDDUPYMask(ShuffleVectorSDNode *N, 3949 const X86Subtarget *Subtarget) { 3950 EVT VT = N->getValueType(0); 3951 int NumElts = VT.getVectorNumElements(); 3952 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF; 3953 3954 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 || 3955 !V2IsUndef || NumElts != 4) 3956 return false; 3957 3958 for (int i = 0; i != NumElts/2; ++i) 3959 if (!isUndefOrEqual(N->getMaskElt(i), 0)) 3960 return false; 3961 for (int i = NumElts/2; i != NumElts; ++i) 3962 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2)) 3963 return false; 3964 return true; 3965} 3966 3967/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3968/// specifies a shuffle of elements that is suitable for input to 128-bit 3969/// version of MOVDDUP. 3970bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) { 3971 EVT VT = N->getValueType(0); 3972 3973 if (VT.getSizeInBits() != 128) 3974 return false; 3975 3976 int e = VT.getVectorNumElements() / 2; 3977 for (int i = 0; i < e; ++i) 3978 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3979 return false; 3980 for (int i = 0; i < e; ++i) 3981 if (!isUndefOrEqual(N->getMaskElt(e+i), i)) 3982 return false; 3983 return true; 3984} 3985 3986/// isVEXTRACTF128Index - Return true if the specified 3987/// EXTRACT_SUBVECTOR operand specifies a vector extract that is 3988/// suitable for input to VEXTRACTF128. 3989bool X86::isVEXTRACTF128Index(SDNode *N) { 3990 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 3991 return false; 3992 3993 // The index should be aligned on a 128-bit boundary. 3994 uint64_t Index = 3995 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 3996 3997 unsigned VL = N->getValueType(0).getVectorNumElements(); 3998 unsigned VBits = N->getValueType(0).getSizeInBits(); 3999 unsigned ElSize = VBits / VL; 4000 bool Result = (Index * ElSize) % 128 == 0; 4001 4002 return Result; 4003} 4004 4005/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR 4006/// operand specifies a subvector insert that is suitable for input to 4007/// VINSERTF128. 4008bool X86::isVINSERTF128Index(SDNode *N) { 4009 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4010 return false; 4011 4012 // The index should be aligned on a 128-bit boundary. 4013 uint64_t Index = 4014 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4015 4016 unsigned VL = N->getValueType(0).getVectorNumElements(); 4017 unsigned VBits = N->getValueType(0).getSizeInBits(); 4018 unsigned ElSize = VBits / VL; 4019 bool Result = (Index * ElSize) % 128 == 0; 4020 4021 return Result; 4022} 4023 4024/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle 4025/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions. 4026unsigned X86::getShuffleSHUFImmediate(SDNode *N) { 4027 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4028 int NumOperands = SVOp->getValueType(0).getVectorNumElements(); 4029 4030 unsigned Shift = (NumOperands == 4) ? 2 : 1; 4031 unsigned Mask = 0; 4032 for (int i = 0; i < NumOperands; ++i) { 4033 int Val = SVOp->getMaskElt(NumOperands-i-1); 4034 if (Val < 0) Val = 0; 4035 if (Val >= NumOperands) Val -= NumOperands; 4036 Mask |= Val; 4037 if (i != NumOperands - 1) 4038 Mask <<= Shift; 4039 } 4040 return Mask; 4041} 4042 4043/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle 4044/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction. 4045unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) { 4046 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4047 unsigned Mask = 0; 4048 // 8 nodes, but we only care about the last 4. 4049 for (unsigned i = 7; i >= 4; --i) { 4050 int Val = SVOp->getMaskElt(i); 4051 if (Val >= 0) 4052 Mask |= (Val - 4); 4053 if (i != 4) 4054 Mask <<= 2; 4055 } 4056 return Mask; 4057} 4058 4059/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle 4060/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction. 4061unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) { 4062 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4063 unsigned Mask = 0; 4064 // 8 nodes, but we only care about the first 4. 4065 for (int i = 3; i >= 0; --i) { 4066 int Val = SVOp->getMaskElt(i); 4067 if (Val >= 0) 4068 Mask |= Val; 4069 if (i != 0) 4070 Mask <<= 2; 4071 } 4072 return Mask; 4073} 4074 4075/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle 4076/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction. 4077unsigned X86::getShufflePALIGNRImmediate(SDNode *N) { 4078 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4079 EVT VVT = N->getValueType(0); 4080 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3; 4081 int Val = 0; 4082 4083 unsigned i, e; 4084 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) { 4085 Val = SVOp->getMaskElt(i); 4086 if (Val >= 0) 4087 break; 4088 } 4089 assert(Val - i > 0 && "PALIGNR imm should be positive"); 4090 return (Val - i) * EltSize; 4091} 4092 4093/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate 4094/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128 4095/// instructions. 4096unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) { 4097 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4098 llvm_unreachable("Illegal extract subvector for VEXTRACTF128"); 4099 4100 uint64_t Index = 4101 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4102 4103 EVT VecVT = N->getOperand(0).getValueType(); 4104 EVT ElVT = VecVT.getVectorElementType(); 4105 4106 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4107 return Index / NumElemsPerChunk; 4108} 4109 4110/// getInsertVINSERTF128Immediate - Return the appropriate immediate 4111/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128 4112/// instructions. 4113unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) { 4114 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4115 llvm_unreachable("Illegal insert subvector for VINSERTF128"); 4116 4117 uint64_t Index = 4118 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4119 4120 EVT VecVT = N->getValueType(0); 4121 EVT ElVT = VecVT.getVectorElementType(); 4122 4123 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4124 return Index / NumElemsPerChunk; 4125} 4126 4127/// isZeroNode - Returns true if Elt is a constant zero or a floating point 4128/// constant +0.0. 4129bool X86::isZeroNode(SDValue Elt) { 4130 return ((isa<ConstantSDNode>(Elt) && 4131 cast<ConstantSDNode>(Elt)->isNullValue()) || 4132 (isa<ConstantFPSDNode>(Elt) && 4133 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero())); 4134} 4135 4136/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in 4137/// their permute mask. 4138static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp, 4139 SelectionDAG &DAG) { 4140 EVT VT = SVOp->getValueType(0); 4141 unsigned NumElems = VT.getVectorNumElements(); 4142 SmallVector<int, 8> MaskVec; 4143 4144 for (unsigned i = 0; i != NumElems; ++i) { 4145 int idx = SVOp->getMaskElt(i); 4146 if (idx < 0) 4147 MaskVec.push_back(idx); 4148 else if (idx < (int)NumElems) 4149 MaskVec.push_back(idx + NumElems); 4150 else 4151 MaskVec.push_back(idx - NumElems); 4152 } 4153 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1), 4154 SVOp->getOperand(0), &MaskVec[0]); 4155} 4156 4157/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming 4158/// the two vector operands have swapped position. 4159static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) { 4160 unsigned NumElems = VT.getVectorNumElements(); 4161 for (unsigned i = 0; i != NumElems; ++i) { 4162 int idx = Mask[i]; 4163 if (idx < 0) 4164 continue; 4165 else if (idx < (int)NumElems) 4166 Mask[i] = idx + NumElems; 4167 else 4168 Mask[i] = idx - NumElems; 4169 } 4170} 4171 4172/// ShouldXformToMOVHLPS - Return true if the node should be transformed to 4173/// match movhlps. The lower half elements should come from upper half of 4174/// V1 (and in order), and the upper half elements should come from the upper 4175/// half of V2 (and in order). 4176static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) { 4177 EVT VT = Op->getValueType(0); 4178 if (VT.getSizeInBits() != 128) 4179 return false; 4180 if (VT.getVectorNumElements() != 4) 4181 return false; 4182 for (unsigned i = 0, e = 2; i != e; ++i) 4183 if (!isUndefOrEqual(Op->getMaskElt(i), i+2)) 4184 return false; 4185 for (unsigned i = 2; i != 4; ++i) 4186 if (!isUndefOrEqual(Op->getMaskElt(i), i+4)) 4187 return false; 4188 return true; 4189} 4190 4191/// isScalarLoadToVector - Returns true if the node is a scalar load that 4192/// is promoted to a vector. It also returns the LoadSDNode by reference if 4193/// required. 4194static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) { 4195 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR) 4196 return false; 4197 N = N->getOperand(0).getNode(); 4198 if (!ISD::isNON_EXTLoad(N)) 4199 return false; 4200 if (LD) 4201 *LD = cast<LoadSDNode>(N); 4202 return true; 4203} 4204 4205/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to 4206/// match movlp{s|d}. The lower half elements should come from lower half of 4207/// V1 (and in order), and the upper half elements should come from the upper 4208/// half of V2 (and in order). And since V1 will become the source of the 4209/// MOVLP, it must be either a vector load or a scalar load to vector. 4210static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, 4211 ShuffleVectorSDNode *Op) { 4212 EVT VT = Op->getValueType(0); 4213 if (VT.getSizeInBits() != 128) 4214 return false; 4215 4216 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1)) 4217 return false; 4218 // Is V2 is a vector load, don't do this transformation. We will try to use 4219 // load folding shufps op. 4220 if (ISD::isNON_EXTLoad(V2)) 4221 return false; 4222 4223 unsigned NumElems = VT.getVectorNumElements(); 4224 4225 if (NumElems != 2 && NumElems != 4) 4226 return false; 4227 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 4228 if (!isUndefOrEqual(Op->getMaskElt(i), i)) 4229 return false; 4230 for (unsigned i = NumElems/2; i != NumElems; ++i) 4231 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems)) 4232 return false; 4233 return true; 4234} 4235 4236/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 4237/// all the same. 4238static bool isSplatVector(SDNode *N) { 4239 if (N->getOpcode() != ISD::BUILD_VECTOR) 4240 return false; 4241 4242 SDValue SplatValue = N->getOperand(0); 4243 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i) 4244 if (N->getOperand(i) != SplatValue) 4245 return false; 4246 return true; 4247} 4248 4249/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved 4250/// to an zero vector. 4251/// FIXME: move to dag combiner / method on ShuffleVectorSDNode 4252static bool isZeroShuffle(ShuffleVectorSDNode *N) { 4253 SDValue V1 = N->getOperand(0); 4254 SDValue V2 = N->getOperand(1); 4255 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 4256 for (unsigned i = 0; i != NumElems; ++i) { 4257 int Idx = N->getMaskElt(i); 4258 if (Idx >= (int)NumElems) { 4259 unsigned Opc = V2.getOpcode(); 4260 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode())) 4261 continue; 4262 if (Opc != ISD::BUILD_VECTOR || 4263 !X86::isZeroNode(V2.getOperand(Idx-NumElems))) 4264 return false; 4265 } else if (Idx >= 0) { 4266 unsigned Opc = V1.getOpcode(); 4267 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode())) 4268 continue; 4269 if (Opc != ISD::BUILD_VECTOR || 4270 !X86::isZeroNode(V1.getOperand(Idx))) 4271 return false; 4272 } 4273 } 4274 return true; 4275} 4276 4277/// getZeroVector - Returns a vector of specified type with all zero elements. 4278/// 4279static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG, 4280 DebugLoc dl) { 4281 assert(VT.isVector() && "Expected a vector type"); 4282 4283 // Always build SSE zero vectors as <4 x i32> bitcasted 4284 // to their dest type. This ensures they get CSE'd. 4285 SDValue Vec; 4286 if (VT.getSizeInBits() == 128) { // SSE 4287 if (HasSSE2) { // SSE2 4288 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4289 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4290 } else { // SSE1 4291 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4292 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst); 4293 } 4294 } else if (VT.getSizeInBits() == 256) { // AVX 4295 // 256-bit logic and arithmetic instructions in AVX are 4296 // all floating-point, no support for integer ops. Default 4297 // to emitting fp zeroed vectors then. 4298 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4299 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4300 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8); 4301 } 4302 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4303} 4304 4305/// getOnesVector - Returns a vector of specified type with all bits set. 4306/// Always build ones vectors as <4 x i32>. For 256-bit types, use two 4307/// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their 4308/// original type, ensuring they get CSE'd. 4309static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) { 4310 assert(VT.isVector() && "Expected a vector type"); 4311 assert((VT.is128BitVector() || VT.is256BitVector()) 4312 && "Expected a 128-bit or 256-bit vector type"); 4313 4314 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32); 4315 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, 4316 Cst, Cst, Cst, Cst); 4317 4318 if (VT.is256BitVector()) { 4319 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32), 4320 Vec, DAG.getConstant(0, MVT::i32), DAG, dl); 4321 Vec = Insert128BitVector(InsV, Vec, 4322 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl); 4323 } 4324 4325 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4326} 4327 4328/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements 4329/// that point to V2 points to its first element. 4330static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 4331 EVT VT = SVOp->getValueType(0); 4332 unsigned NumElems = VT.getVectorNumElements(); 4333 4334 bool Changed = false; 4335 SmallVector<int, 8> MaskVec; 4336 SVOp->getMask(MaskVec); 4337 4338 for (unsigned i = 0; i != NumElems; ++i) { 4339 if (MaskVec[i] > (int)NumElems) { 4340 MaskVec[i] = NumElems; 4341 Changed = true; 4342 } 4343 } 4344 if (Changed) 4345 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0), 4346 SVOp->getOperand(1), &MaskVec[0]); 4347 return SDValue(SVOp, 0); 4348} 4349 4350/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd 4351/// operation of specified width. 4352static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4353 SDValue V2) { 4354 unsigned NumElems = VT.getVectorNumElements(); 4355 SmallVector<int, 8> Mask; 4356 Mask.push_back(NumElems); 4357 for (unsigned i = 1; i != NumElems; ++i) 4358 Mask.push_back(i); 4359 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4360} 4361 4362/// getUnpackl - Returns a vector_shuffle node for an unpackl operation. 4363static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4364 SDValue V2) { 4365 unsigned NumElems = VT.getVectorNumElements(); 4366 SmallVector<int, 8> Mask; 4367 for (unsigned i = 0, e = NumElems/2; i != e; ++i) { 4368 Mask.push_back(i); 4369 Mask.push_back(i + NumElems); 4370 } 4371 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4372} 4373 4374/// getUnpackh - Returns a vector_shuffle node for an unpackh operation. 4375static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4376 SDValue V2) { 4377 unsigned NumElems = VT.getVectorNumElements(); 4378 unsigned Half = NumElems/2; 4379 SmallVector<int, 8> Mask; 4380 for (unsigned i = 0; i != Half; ++i) { 4381 Mask.push_back(i + Half); 4382 Mask.push_back(i + NumElems + Half); 4383 } 4384 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4385} 4386 4387// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by 4388// a generic shuffle instruction because the target has no such instructions. 4389// Generate shuffles which repeat i16 and i8 several times until they can be 4390// represented by v4f32 and then be manipulated by target suported shuffles. 4391static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) { 4392 EVT VT = V.getValueType(); 4393 int NumElems = VT.getVectorNumElements(); 4394 DebugLoc dl = V.getDebugLoc(); 4395 4396 while (NumElems > 4) { 4397 if (EltNo < NumElems/2) { 4398 V = getUnpackl(DAG, dl, VT, V, V); 4399 } else { 4400 V = getUnpackh(DAG, dl, VT, V, V); 4401 EltNo -= NumElems/2; 4402 } 4403 NumElems >>= 1; 4404 } 4405 return V; 4406} 4407 4408/// getLegalSplat - Generate a legal splat with supported x86 shuffles 4409static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) { 4410 EVT VT = V.getValueType(); 4411 DebugLoc dl = V.getDebugLoc(); 4412 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256) 4413 && "Vector size not supported"); 4414 4415 if (VT.getSizeInBits() == 128) { 4416 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V); 4417 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo }; 4418 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32), 4419 &SplatMask[0]); 4420 } else { 4421 // To use VPERMILPS to splat scalars, the second half of indicies must 4422 // refer to the higher part, which is a duplication of the lower one, 4423 // because VPERMILPS can only handle in-lane permutations. 4424 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo, 4425 EltNo+4, EltNo+4, EltNo+4, EltNo+4 }; 4426 4427 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V); 4428 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32), 4429 &SplatMask[0]); 4430 } 4431 4432 return DAG.getNode(ISD::BITCAST, dl, VT, V); 4433} 4434 4435/// PromoteSplat - Splat is promoted to target supported vector shuffles. 4436static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) { 4437 EVT SrcVT = SV->getValueType(0); 4438 SDValue V1 = SV->getOperand(0); 4439 DebugLoc dl = SV->getDebugLoc(); 4440 4441 int EltNo = SV->getSplatIndex(); 4442 int NumElems = SrcVT.getVectorNumElements(); 4443 unsigned Size = SrcVT.getSizeInBits(); 4444 4445 assert(((Size == 128 && NumElems > 4) || Size == 256) && 4446 "Unknown how to promote splat for type"); 4447 4448 // Extract the 128-bit part containing the splat element and update 4449 // the splat element index when it refers to the higher register. 4450 if (Size == 256) { 4451 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0; 4452 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl); 4453 if (Idx > 0) 4454 EltNo -= NumElems/2; 4455 } 4456 4457 // All i16 and i8 vector types can't be used directly by a generic shuffle 4458 // instruction because the target has no such instruction. Generate shuffles 4459 // which repeat i16 and i8 several times until they fit in i32, and then can 4460 // be manipulated by target suported shuffles. 4461 EVT EltVT = SrcVT.getVectorElementType(); 4462 if (EltVT == MVT::i8 || EltVT == MVT::i16) 4463 V1 = PromoteSplati8i16(V1, DAG, EltNo); 4464 4465 // Recreate the 256-bit vector and place the same 128-bit vector 4466 // into the low and high part. This is necessary because we want 4467 // to use VPERM* to shuffle the vectors 4468 if (Size == 256) { 4469 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1, 4470 DAG.getConstant(0, MVT::i32), DAG, dl); 4471 V1 = Insert128BitVector(InsV, V1, 4472 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl); 4473 } 4474 4475 return getLegalSplat(DAG, V1, EltNo); 4476} 4477 4478/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified 4479/// vector of zero or undef vector. This produces a shuffle where the low 4480/// element of V2 is swizzled into the zero/undef vector, landing at element 4481/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3). 4482static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx, 4483 bool isZero, bool HasSSE2, 4484 SelectionDAG &DAG) { 4485 EVT VT = V2.getValueType(); 4486 SDValue V1 = isZero 4487 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT); 4488 unsigned NumElems = VT.getVectorNumElements(); 4489 SmallVector<int, 16> MaskVec; 4490 for (unsigned i = 0; i != NumElems; ++i) 4491 // If this is the insertion idx, put the low elt of V2 here. 4492 MaskVec.push_back(i == Idx ? NumElems : i); 4493 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]); 4494} 4495 4496/// getShuffleScalarElt - Returns the scalar element that will make up the ith 4497/// element of the result of the vector shuffle. 4498static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG, 4499 unsigned Depth) { 4500 if (Depth == 6) 4501 return SDValue(); // Limit search depth. 4502 4503 SDValue V = SDValue(N, 0); 4504 EVT VT = V.getValueType(); 4505 unsigned Opcode = V.getOpcode(); 4506 4507 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars. 4508 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) { 4509 Index = SV->getMaskElt(Index); 4510 4511 if (Index < 0) 4512 return DAG.getUNDEF(VT.getVectorElementType()); 4513 4514 int NumElems = VT.getVectorNumElements(); 4515 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1); 4516 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1); 4517 } 4518 4519 // Recurse into target specific vector shuffles to find scalars. 4520 if (isTargetShuffle(Opcode)) { 4521 int NumElems = VT.getVectorNumElements(); 4522 SmallVector<unsigned, 16> ShuffleMask; 4523 SDValue ImmN; 4524 4525 switch(Opcode) { 4526 case X86ISD::SHUFPS: 4527 case X86ISD::SHUFPD: 4528 ImmN = N->getOperand(N->getNumOperands()-1); 4529 DecodeSHUFPSMask(NumElems, 4530 cast<ConstantSDNode>(ImmN)->getZExtValue(), 4531 ShuffleMask); 4532 break; 4533 case X86ISD::PUNPCKHBW: 4534 case X86ISD::PUNPCKHWD: 4535 case X86ISD::PUNPCKHDQ: 4536 case X86ISD::PUNPCKHQDQ: 4537 DecodePUNPCKHMask(NumElems, ShuffleMask); 4538 break; 4539 case X86ISD::UNPCKHPS: 4540 case X86ISD::UNPCKHPD: 4541 case X86ISD::VUNPCKHPSY: 4542 case X86ISD::VUNPCKHPDY: 4543 DecodeUNPCKHPMask(NumElems, ShuffleMask); 4544 break; 4545 case X86ISD::PUNPCKLBW: 4546 case X86ISD::PUNPCKLWD: 4547 case X86ISD::PUNPCKLDQ: 4548 case X86ISD::PUNPCKLQDQ: 4549 DecodePUNPCKLMask(VT, ShuffleMask); 4550 break; 4551 case X86ISD::UNPCKLPS: 4552 case X86ISD::UNPCKLPD: 4553 case X86ISD::VUNPCKLPSY: 4554 case X86ISD::VUNPCKLPDY: 4555 DecodeUNPCKLPMask(VT, ShuffleMask); 4556 break; 4557 case X86ISD::MOVHLPS: 4558 DecodeMOVHLPSMask(NumElems, ShuffleMask); 4559 break; 4560 case X86ISD::MOVLHPS: 4561 DecodeMOVLHPSMask(NumElems, ShuffleMask); 4562 break; 4563 case X86ISD::PSHUFD: 4564 ImmN = N->getOperand(N->getNumOperands()-1); 4565 DecodePSHUFMask(NumElems, 4566 cast<ConstantSDNode>(ImmN)->getZExtValue(), 4567 ShuffleMask); 4568 break; 4569 case X86ISD::PSHUFHW: 4570 ImmN = N->getOperand(N->getNumOperands()-1); 4571 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 4572 ShuffleMask); 4573 break; 4574 case X86ISD::PSHUFLW: 4575 ImmN = N->getOperand(N->getNumOperands()-1); 4576 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 4577 ShuffleMask); 4578 break; 4579 case X86ISD::MOVSS: 4580 case X86ISD::MOVSD: { 4581 // The index 0 always comes from the first element of the second source, 4582 // this is why MOVSS and MOVSD are used in the first place. The other 4583 // elements come from the other positions of the first source vector. 4584 unsigned OpNum = (Index == 0) ? 1 : 0; 4585 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG, 4586 Depth+1); 4587 } 4588 case X86ISD::VPERMILPS: 4589 ImmN = N->getOperand(N->getNumOperands()-1); 4590 DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4591 ShuffleMask); 4592 break; 4593 case X86ISD::VPERMILPSY: 4594 ImmN = N->getOperand(N->getNumOperands()-1); 4595 DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4596 ShuffleMask); 4597 break; 4598 case X86ISD::VPERMILPD: 4599 ImmN = N->getOperand(N->getNumOperands()-1); 4600 DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4601 ShuffleMask); 4602 break; 4603 case X86ISD::VPERMILPDY: 4604 ImmN = N->getOperand(N->getNumOperands()-1); 4605 DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4606 ShuffleMask); 4607 break; 4608 case X86ISD::VPERM2F128: 4609 ImmN = N->getOperand(N->getNumOperands()-1); 4610 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4611 ShuffleMask); 4612 break; 4613 default: 4614 assert("not implemented for target shuffle node"); 4615 return SDValue(); 4616 } 4617 4618 Index = ShuffleMask[Index]; 4619 if (Index < 0) 4620 return DAG.getUNDEF(VT.getVectorElementType()); 4621 4622 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1); 4623 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, 4624 Depth+1); 4625 } 4626 4627 // Actual nodes that may contain scalar elements 4628 if (Opcode == ISD::BITCAST) { 4629 V = V.getOperand(0); 4630 EVT SrcVT = V.getValueType(); 4631 unsigned NumElems = VT.getVectorNumElements(); 4632 4633 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems) 4634 return SDValue(); 4635 } 4636 4637 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 4638 return (Index == 0) ? V.getOperand(0) 4639 : DAG.getUNDEF(VT.getVectorElementType()); 4640 4641 if (V.getOpcode() == ISD::BUILD_VECTOR) 4642 return V.getOperand(Index); 4643 4644 return SDValue(); 4645} 4646 4647/// getNumOfConsecutiveZeros - Return the number of elements of a vector 4648/// shuffle operation which come from a consecutively from a zero. The 4649/// search can start in two different directions, from left or right. 4650static 4651unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems, 4652 bool ZerosFromLeft, SelectionDAG &DAG) { 4653 int i = 0; 4654 4655 while (i < NumElems) { 4656 unsigned Index = ZerosFromLeft ? i : NumElems-i-1; 4657 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0); 4658 if (!(Elt.getNode() && 4659 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt)))) 4660 break; 4661 ++i; 4662 } 4663 4664 return i; 4665} 4666 4667/// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to 4668/// MaskE correspond consecutively to elements from one of the vector operands, 4669/// starting from its index OpIdx. Also tell OpNum which source vector operand. 4670static 4671bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE, 4672 int OpIdx, int NumElems, unsigned &OpNum) { 4673 bool SeenV1 = false; 4674 bool SeenV2 = false; 4675 4676 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) { 4677 int Idx = SVOp->getMaskElt(i); 4678 // Ignore undef indicies 4679 if (Idx < 0) 4680 continue; 4681 4682 if (Idx < NumElems) 4683 SeenV1 = true; 4684 else 4685 SeenV2 = true; 4686 4687 // Only accept consecutive elements from the same vector 4688 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2)) 4689 return false; 4690 } 4691 4692 OpNum = SeenV1 ? 0 : 1; 4693 return true; 4694} 4695 4696/// isVectorShiftRight - Returns true if the shuffle can be implemented as a 4697/// logical left shift of a vector. 4698static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4699 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4700 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4701 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4702 false /* check zeros from right */, DAG); 4703 unsigned OpSrc; 4704 4705 if (!NumZeros) 4706 return false; 4707 4708 // Considering the elements in the mask that are not consecutive zeros, 4709 // check if they consecutively come from only one of the source vectors. 4710 // 4711 // V1 = {X, A, B, C} 0 4712 // \ \ \ / 4713 // vector_shuffle V1, V2 <1, 2, 3, X> 4714 // 4715 if (!isShuffleMaskConsecutive(SVOp, 4716 0, // Mask Start Index 4717 NumElems-NumZeros-1, // Mask End Index 4718 NumZeros, // Where to start looking in the src vector 4719 NumElems, // Number of elements in vector 4720 OpSrc)) // Which source operand ? 4721 return false; 4722 4723 isLeft = false; 4724 ShAmt = NumZeros; 4725 ShVal = SVOp->getOperand(OpSrc); 4726 return true; 4727} 4728 4729/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a 4730/// logical left shift of a vector. 4731static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4732 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4733 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4734 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4735 true /* check zeros from left */, DAG); 4736 unsigned OpSrc; 4737 4738 if (!NumZeros) 4739 return false; 4740 4741 // Considering the elements in the mask that are not consecutive zeros, 4742 // check if they consecutively come from only one of the source vectors. 4743 // 4744 // 0 { A, B, X, X } = V2 4745 // / \ / / 4746 // vector_shuffle V1, V2 <X, X, 4, 5> 4747 // 4748 if (!isShuffleMaskConsecutive(SVOp, 4749 NumZeros, // Mask Start Index 4750 NumElems-1, // Mask End Index 4751 0, // Where to start looking in the src vector 4752 NumElems, // Number of elements in vector 4753 OpSrc)) // Which source operand ? 4754 return false; 4755 4756 isLeft = true; 4757 ShAmt = NumZeros; 4758 ShVal = SVOp->getOperand(OpSrc); 4759 return true; 4760} 4761 4762/// isVectorShift - Returns true if the shuffle can be implemented as a 4763/// logical left or right shift of a vector. 4764static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4765 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4766 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) || 4767 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt)) 4768 return true; 4769 4770 return false; 4771} 4772 4773/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8. 4774/// 4775static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros, 4776 unsigned NumNonZero, unsigned NumZero, 4777 SelectionDAG &DAG, 4778 const TargetLowering &TLI) { 4779 if (NumNonZero > 8) 4780 return SDValue(); 4781 4782 DebugLoc dl = Op.getDebugLoc(); 4783 SDValue V(0, 0); 4784 bool First = true; 4785 for (unsigned i = 0; i < 16; ++i) { 4786 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0; 4787 if (ThisIsNonZero && First) { 4788 if (NumZero) 4789 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4790 else 4791 V = DAG.getUNDEF(MVT::v8i16); 4792 First = false; 4793 } 4794 4795 if ((i & 1) != 0) { 4796 SDValue ThisElt(0, 0), LastElt(0, 0); 4797 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0; 4798 if (LastIsNonZero) { 4799 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl, 4800 MVT::i16, Op.getOperand(i-1)); 4801 } 4802 if (ThisIsNonZero) { 4803 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i)); 4804 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, 4805 ThisElt, DAG.getConstant(8, MVT::i8)); 4806 if (LastIsNonZero) 4807 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt); 4808 } else 4809 ThisElt = LastElt; 4810 4811 if (ThisElt.getNode()) 4812 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt, 4813 DAG.getIntPtrConstant(i/2)); 4814 } 4815 } 4816 4817 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V); 4818} 4819 4820/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16. 4821/// 4822static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros, 4823 unsigned NumNonZero, unsigned NumZero, 4824 SelectionDAG &DAG, 4825 const TargetLowering &TLI) { 4826 if (NumNonZero > 4) 4827 return SDValue(); 4828 4829 DebugLoc dl = Op.getDebugLoc(); 4830 SDValue V(0, 0); 4831 bool First = true; 4832 for (unsigned i = 0; i < 8; ++i) { 4833 bool isNonZero = (NonZeros & (1 << i)) != 0; 4834 if (isNonZero) { 4835 if (First) { 4836 if (NumZero) 4837 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4838 else 4839 V = DAG.getUNDEF(MVT::v8i16); 4840 First = false; 4841 } 4842 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, 4843 MVT::v8i16, V, Op.getOperand(i), 4844 DAG.getIntPtrConstant(i)); 4845 } 4846 } 4847 4848 return V; 4849} 4850 4851/// getVShift - Return a vector logical shift node. 4852/// 4853static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, 4854 unsigned NumBits, SelectionDAG &DAG, 4855 const TargetLowering &TLI, DebugLoc dl) { 4856 EVT ShVT = MVT::v2i64; 4857 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL; 4858 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp); 4859 return DAG.getNode(ISD::BITCAST, dl, VT, 4860 DAG.getNode(Opc, dl, ShVT, SrcOp, 4861 DAG.getConstant(NumBits, 4862 TLI.getShiftAmountTy(SrcOp.getValueType())))); 4863} 4864 4865SDValue 4866X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl, 4867 SelectionDAG &DAG) const { 4868 4869 // Check if the scalar load can be widened into a vector load. And if 4870 // the address is "base + cst" see if the cst can be "absorbed" into 4871 // the shuffle mask. 4872 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) { 4873 SDValue Ptr = LD->getBasePtr(); 4874 if (!ISD::isNormalLoad(LD) || LD->isVolatile()) 4875 return SDValue(); 4876 EVT PVT = LD->getValueType(0); 4877 if (PVT != MVT::i32 && PVT != MVT::f32) 4878 return SDValue(); 4879 4880 int FI = -1; 4881 int64_t Offset = 0; 4882 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) { 4883 FI = FINode->getIndex(); 4884 Offset = 0; 4885 } else if (DAG.isBaseWithConstantOffset(Ptr) && 4886 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 4887 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 4888 Offset = Ptr.getConstantOperandVal(1); 4889 Ptr = Ptr.getOperand(0); 4890 } else { 4891 return SDValue(); 4892 } 4893 4894 // FIXME: 256-bit vector instructions don't require a strict alignment, 4895 // improve this code to support it better. 4896 unsigned RequiredAlign = VT.getSizeInBits()/8; 4897 SDValue Chain = LD->getChain(); 4898 // Make sure the stack object alignment is at least 16 or 32. 4899 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4900 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) { 4901 if (MFI->isFixedObjectIndex(FI)) { 4902 // Can't change the alignment. FIXME: It's possible to compute 4903 // the exact stack offset and reference FI + adjust offset instead. 4904 // If someone *really* cares about this. That's the way to implement it. 4905 return SDValue(); 4906 } else { 4907 MFI->setObjectAlignment(FI, RequiredAlign); 4908 } 4909 } 4910 4911 // (Offset % 16 or 32) must be multiple of 4. Then address is then 4912 // Ptr + (Offset & ~15). 4913 if (Offset < 0) 4914 return SDValue(); 4915 if ((Offset % RequiredAlign) & 3) 4916 return SDValue(); 4917 int64_t StartOffset = Offset & ~(RequiredAlign-1); 4918 if (StartOffset) 4919 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(), 4920 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType())); 4921 4922 int EltNo = (Offset - StartOffset) >> 2; 4923 int NumElems = VT.getVectorNumElements(); 4924 4925 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32; 4926 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems); 4927 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr, 4928 LD->getPointerInfo().getWithOffset(StartOffset), 4929 false, false, 0); 4930 4931 // Canonicalize it to a v4i32 or v8i32 shuffle. 4932 SmallVector<int, 8> Mask; 4933 for (int i = 0; i < NumElems; ++i) 4934 Mask.push_back(EltNo); 4935 4936 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1); 4937 return DAG.getNode(ISD::BITCAST, dl, NVT, 4938 DAG.getVectorShuffle(CanonVT, dl, V1, 4939 DAG.getUNDEF(CanonVT),&Mask[0])); 4940 } 4941 4942 return SDValue(); 4943} 4944 4945/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 4946/// vector of type 'VT', see if the elements can be replaced by a single large 4947/// load which has the same value as a build_vector whose operands are 'elts'. 4948/// 4949/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a 4950/// 4951/// FIXME: we'd also like to handle the case where the last elements are zero 4952/// rather than undef via VZEXT_LOAD, but we do not detect that case today. 4953/// There's even a handy isZeroNode for that purpose. 4954static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts, 4955 DebugLoc &DL, SelectionDAG &DAG) { 4956 EVT EltVT = VT.getVectorElementType(); 4957 unsigned NumElems = Elts.size(); 4958 4959 LoadSDNode *LDBase = NULL; 4960 unsigned LastLoadedElt = -1U; 4961 4962 // For each element in the initializer, see if we've found a load or an undef. 4963 // If we don't find an initial load element, or later load elements are 4964 // non-consecutive, bail out. 4965 for (unsigned i = 0; i < NumElems; ++i) { 4966 SDValue Elt = Elts[i]; 4967 4968 if (!Elt.getNode() || 4969 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode()))) 4970 return SDValue(); 4971 if (!LDBase) { 4972 if (Elt.getNode()->getOpcode() == ISD::UNDEF) 4973 return SDValue(); 4974 LDBase = cast<LoadSDNode>(Elt.getNode()); 4975 LastLoadedElt = i; 4976 continue; 4977 } 4978 if (Elt.getOpcode() == ISD::UNDEF) 4979 continue; 4980 4981 LoadSDNode *LD = cast<LoadSDNode>(Elt); 4982 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i)) 4983 return SDValue(); 4984 LastLoadedElt = i; 4985 } 4986 4987 // If we have found an entire vector of loads and undefs, then return a large 4988 // load of the entire vector width starting at the base pointer. If we found 4989 // consecutive loads for the low half, generate a vzext_load node. 4990 if (LastLoadedElt == NumElems - 1) { 4991 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16) 4992 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 4993 LDBase->getPointerInfo(), 4994 LDBase->isVolatile(), LDBase->isNonTemporal(), 0); 4995 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 4996 LDBase->getPointerInfo(), 4997 LDBase->isVolatile(), LDBase->isNonTemporal(), 4998 LDBase->getAlignment()); 4999 } else if (NumElems == 4 && LastLoadedElt == 1 && 5000 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) { 5001 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other); 5002 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() }; 5003 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, 5004 Ops, 2, MVT::i32, 5005 LDBase->getMemOperand()); 5006 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode); 5007 } 5008 return SDValue(); 5009} 5010 5011SDValue 5012X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { 5013 DebugLoc dl = Op.getDebugLoc(); 5014 5015 EVT VT = Op.getValueType(); 5016 EVT ExtVT = VT.getVectorElementType(); 5017 unsigned NumElems = Op.getNumOperands(); 5018 5019 // Vectors containing all zeros can be matched by pxor and xorps later 5020 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 5021 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd 5022 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts. 5023 if (Op.getValueType() == MVT::v4i32 || 5024 Op.getValueType() == MVT::v8i32) 5025 return Op; 5026 5027 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl); 5028 } 5029 5030 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width 5031 // vectors or broken into v4i32 operations on 256-bit vectors. 5032 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 5033 if (Op.getValueType() == MVT::v4i32) 5034 return Op; 5035 5036 return getOnesVector(Op.getValueType(), DAG, dl); 5037 } 5038 5039 unsigned EVTBits = ExtVT.getSizeInBits(); 5040 5041 unsigned NumZero = 0; 5042 unsigned NumNonZero = 0; 5043 unsigned NonZeros = 0; 5044 bool IsAllConstants = true; 5045 SmallSet<SDValue, 8> Values; 5046 for (unsigned i = 0; i < NumElems; ++i) { 5047 SDValue Elt = Op.getOperand(i); 5048 if (Elt.getOpcode() == ISD::UNDEF) 5049 continue; 5050 Values.insert(Elt); 5051 if (Elt.getOpcode() != ISD::Constant && 5052 Elt.getOpcode() != ISD::ConstantFP) 5053 IsAllConstants = false; 5054 if (X86::isZeroNode(Elt)) 5055 NumZero++; 5056 else { 5057 NonZeros |= (1 << i); 5058 NumNonZero++; 5059 } 5060 } 5061 5062 // All undef vector. Return an UNDEF. All zero vectors were handled above. 5063 if (NumNonZero == 0) 5064 return DAG.getUNDEF(VT); 5065 5066 // Special case for single non-zero, non-undef, element. 5067 if (NumNonZero == 1) { 5068 unsigned Idx = CountTrailingZeros_32(NonZeros); 5069 SDValue Item = Op.getOperand(Idx); 5070 5071 // If this is an insertion of an i64 value on x86-32, and if the top bits of 5072 // the value are obviously zero, truncate the value to i32 and do the 5073 // insertion that way. Only do this if the value is non-constant or if the 5074 // value is a constant being inserted into element 0. It is cheaper to do 5075 // a constant pool load than it is to do a movd + shuffle. 5076 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() && 5077 (!IsAllConstants || Idx == 0)) { 5078 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) { 5079 // Handle SSE only. 5080 assert(VT == MVT::v2i64 && "Expected an SSE value type!"); 5081 EVT VecVT = MVT::v4i32; 5082 unsigned VecElts = 4; 5083 5084 // Truncate the value (which may itself be a constant) to i32, and 5085 // convert it to a vector with movd (S2V+shuffle to zero extend). 5086 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item); 5087 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item); 5088 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 5089 Subtarget->hasSSE2(), DAG); 5090 5091 // Now we have our 32-bit value zero extended in the low element of 5092 // a vector. If Idx != 0, swizzle it into place. 5093 if (Idx != 0) { 5094 SmallVector<int, 4> Mask; 5095 Mask.push_back(Idx); 5096 for (unsigned i = 1; i != VecElts; ++i) 5097 Mask.push_back(i); 5098 Item = DAG.getVectorShuffle(VecVT, dl, Item, 5099 DAG.getUNDEF(Item.getValueType()), 5100 &Mask[0]); 5101 } 5102 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item); 5103 } 5104 } 5105 5106 // If we have a constant or non-constant insertion into the low element of 5107 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into 5108 // the rest of the elements. This will be matched as movd/movq/movss/movsd 5109 // depending on what the source datatype is. 5110 if (Idx == 0) { 5111 if (NumZero == 0) { 5112 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5113 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 || 5114 (ExtVT == MVT::i64 && Subtarget->is64Bit())) { 5115 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5116 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector. 5117 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(), 5118 DAG); 5119 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) { 5120 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item); 5121 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!"); 5122 EVT MiddleVT = MVT::v4i32; 5123 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item); 5124 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 5125 Subtarget->hasSSE2(), DAG); 5126 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5127 } 5128 } 5129 5130 // Is it a vector logical left shift? 5131 if (NumElems == 2 && Idx == 1 && 5132 X86::isZeroNode(Op.getOperand(0)) && 5133 !X86::isZeroNode(Op.getOperand(1))) { 5134 unsigned NumBits = VT.getSizeInBits(); 5135 return getVShift(true, VT, 5136 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5137 VT, Op.getOperand(1)), 5138 NumBits/2, DAG, *this, dl); 5139 } 5140 5141 if (IsAllConstants) // Otherwise, it's better to do a constpool load. 5142 return SDValue(); 5143 5144 // Otherwise, if this is a vector with i32 or f32 elements, and the element 5145 // is a non-constant being inserted into an element other than the low one, 5146 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka 5147 // movd/movss) to move this into the low element, then shuffle it into 5148 // place. 5149 if (EVTBits == 32) { 5150 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5151 5152 // Turn it into a shuffle of zero and zero-extended scalar to vector. 5153 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, 5154 Subtarget->hasSSE2(), DAG); 5155 SmallVector<int, 8> MaskVec; 5156 for (unsigned i = 0; i < NumElems; i++) 5157 MaskVec.push_back(i == Idx ? 0 : 1); 5158 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]); 5159 } 5160 } 5161 5162 // Splat is obviously ok. Let legalizer expand it to a shuffle. 5163 if (Values.size() == 1) { 5164 if (EVTBits == 32) { 5165 // Instead of a shuffle like this: 5166 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0> 5167 // Check if it's possible to issue this instead. 5168 // shuffle (vload ptr)), undef, <1, 1, 1, 1> 5169 unsigned Idx = CountTrailingZeros_32(NonZeros); 5170 SDValue Item = Op.getOperand(Idx); 5171 if (Op.getNode()->isOnlyUserOf(Item.getNode())) 5172 return LowerAsSplatVectorLoad(Item, VT, dl, DAG); 5173 } 5174 return SDValue(); 5175 } 5176 5177 // A vector full of immediates; various special cases are already 5178 // handled, so this is best done with a single constant-pool load. 5179 if (IsAllConstants) 5180 return SDValue(); 5181 5182 // For AVX-length vectors, build the individual 128-bit pieces and use 5183 // shuffles to put them in place. 5184 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) { 5185 SmallVector<SDValue, 32> V; 5186 for (unsigned i = 0; i < NumElems; ++i) 5187 V.push_back(Op.getOperand(i)); 5188 5189 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2); 5190 5191 // Build both the lower and upper subvector. 5192 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2); 5193 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2], 5194 NumElems/2); 5195 5196 // Recreate the wider vector with the lower and upper part. 5197 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower, 5198 DAG.getConstant(0, MVT::i32), DAG, dl); 5199 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32), 5200 DAG, dl); 5201 } 5202 5203 // Let legalizer expand 2-wide build_vectors. 5204 if (EVTBits == 64) { 5205 if (NumNonZero == 1) { 5206 // One half is zero or undef. 5207 unsigned Idx = CountTrailingZeros_32(NonZeros); 5208 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, 5209 Op.getOperand(Idx)); 5210 return getShuffleVectorZeroOrUndef(V2, Idx, true, 5211 Subtarget->hasSSE2(), DAG); 5212 } 5213 return SDValue(); 5214 } 5215 5216 // If element VT is < 32 bits, convert it to inserts into a zero vector. 5217 if (EVTBits == 8 && NumElems == 16) { 5218 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG, 5219 *this); 5220 if (V.getNode()) return V; 5221 } 5222 5223 if (EVTBits == 16 && NumElems == 8) { 5224 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG, 5225 *this); 5226 if (V.getNode()) return V; 5227 } 5228 5229 // If element VT is == 32 bits, turn it into a number of shuffles. 5230 SmallVector<SDValue, 8> V; 5231 V.resize(NumElems); 5232 if (NumElems == 4 && NumZero > 0) { 5233 for (unsigned i = 0; i < 4; ++i) { 5234 bool isZero = !(NonZeros & (1 << i)); 5235 if (isZero) 5236 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl); 5237 else 5238 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5239 } 5240 5241 for (unsigned i = 0; i < 2; ++i) { 5242 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) { 5243 default: break; 5244 case 0: 5245 V[i] = V[i*2]; // Must be a zero vector. 5246 break; 5247 case 1: 5248 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]); 5249 break; 5250 case 2: 5251 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]); 5252 break; 5253 case 3: 5254 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]); 5255 break; 5256 } 5257 } 5258 5259 SmallVector<int, 8> MaskVec; 5260 bool Reverse = (NonZeros & 0x3) == 2; 5261 for (unsigned i = 0; i < 2; ++i) 5262 MaskVec.push_back(Reverse ? 1-i : i); 5263 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2; 5264 for (unsigned i = 0; i < 2; ++i) 5265 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems); 5266 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]); 5267 } 5268 5269 if (Values.size() > 1 && VT.getSizeInBits() == 128) { 5270 // Check for a build vector of consecutive loads. 5271 for (unsigned i = 0; i < NumElems; ++i) 5272 V[i] = Op.getOperand(i); 5273 5274 // Check for elements which are consecutive loads. 5275 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG); 5276 if (LD.getNode()) 5277 return LD; 5278 5279 // For SSE 4.1, use insertps to put the high elements into the low element. 5280 if (getSubtarget()->hasSSE41()) { 5281 SDValue Result; 5282 if (Op.getOperand(0).getOpcode() != ISD::UNDEF) 5283 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0)); 5284 else 5285 Result = DAG.getUNDEF(VT); 5286 5287 for (unsigned i = 1; i < NumElems; ++i) { 5288 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue; 5289 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result, 5290 Op.getOperand(i), DAG.getIntPtrConstant(i)); 5291 } 5292 return Result; 5293 } 5294 5295 // Otherwise, expand into a number of unpckl*, start by extending each of 5296 // our (non-undef) elements to the full vector width with the element in the 5297 // bottom slot of the vector (which generates no code for SSE). 5298 for (unsigned i = 0; i < NumElems; ++i) { 5299 if (Op.getOperand(i).getOpcode() != ISD::UNDEF) 5300 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5301 else 5302 V[i] = DAG.getUNDEF(VT); 5303 } 5304 5305 // Next, we iteratively mix elements, e.g. for v4f32: 5306 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0> 5307 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1> 5308 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0> 5309 unsigned EltStride = NumElems >> 1; 5310 while (EltStride != 0) { 5311 for (unsigned i = 0; i < EltStride; ++i) { 5312 // If V[i+EltStride] is undef and this is the first round of mixing, 5313 // then it is safe to just drop this shuffle: V[i] is already in the 5314 // right place, the one element (since it's the first round) being 5315 // inserted as undef can be dropped. This isn't safe for successive 5316 // rounds because they will permute elements within both vectors. 5317 if (V[i+EltStride].getOpcode() == ISD::UNDEF && 5318 EltStride == NumElems/2) 5319 continue; 5320 5321 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]); 5322 } 5323 EltStride >>= 1; 5324 } 5325 return V[0]; 5326 } 5327 return SDValue(); 5328} 5329 5330// LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place 5331// them in a MMX register. This is better than doing a stack convert. 5332static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5333 DebugLoc dl = Op.getDebugLoc(); 5334 EVT ResVT = Op.getValueType(); 5335 5336 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 || 5337 ResVT == MVT::v8i16 || ResVT == MVT::v16i8); 5338 int Mask[2]; 5339 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0)); 5340 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 5341 InVec = Op.getOperand(1); 5342 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5343 unsigned NumElts = ResVT.getVectorNumElements(); 5344 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 5345 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp, 5346 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1)); 5347 } else { 5348 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec); 5349 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 5350 Mask[0] = 0; Mask[1] = 2; 5351 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask); 5352 } 5353 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 5354} 5355 5356// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction 5357// to create 256-bit vectors from two other 128-bit ones. 5358static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5359 DebugLoc dl = Op.getDebugLoc(); 5360 EVT ResVT = Op.getValueType(); 5361 5362 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide"); 5363 5364 SDValue V1 = Op.getOperand(0); 5365 SDValue V2 = Op.getOperand(1); 5366 unsigned NumElems = ResVT.getVectorNumElements(); 5367 5368 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1, 5369 DAG.getConstant(0, MVT::i32), DAG, dl); 5370 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32), 5371 DAG, dl); 5372} 5373 5374SDValue 5375X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const { 5376 EVT ResVT = Op.getValueType(); 5377 5378 assert(Op.getNumOperands() == 2); 5379 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) && 5380 "Unsupported CONCAT_VECTORS for value type"); 5381 5382 // We support concatenate two MMX registers and place them in a MMX register. 5383 // This is better than doing a stack convert. 5384 if (ResVT.is128BitVector()) 5385 return LowerMMXCONCAT_VECTORS(Op, DAG); 5386 5387 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors 5388 // from two other 128-bit ones. 5389 return LowerAVXCONCAT_VECTORS(Op, DAG); 5390} 5391 5392// v8i16 shuffles - Prefer shuffles in the following order: 5393// 1. [all] pshuflw, pshufhw, optional move 5394// 2. [ssse3] 1 x pshufb 5395// 3. [ssse3] 2 x pshufb + 1 x por 5396// 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw) 5397SDValue 5398X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op, 5399 SelectionDAG &DAG) const { 5400 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5401 SDValue V1 = SVOp->getOperand(0); 5402 SDValue V2 = SVOp->getOperand(1); 5403 DebugLoc dl = SVOp->getDebugLoc(); 5404 SmallVector<int, 8> MaskVals; 5405 5406 // Determine if more than 1 of the words in each of the low and high quadwords 5407 // of the result come from the same quadword of one of the two inputs. Undef 5408 // mask values count as coming from any quadword, for better codegen. 5409 SmallVector<unsigned, 4> LoQuad(4); 5410 SmallVector<unsigned, 4> HiQuad(4); 5411 BitVector InputQuads(4); 5412 for (unsigned i = 0; i < 8; ++i) { 5413 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad; 5414 int EltIdx = SVOp->getMaskElt(i); 5415 MaskVals.push_back(EltIdx); 5416 if (EltIdx < 0) { 5417 ++Quad[0]; 5418 ++Quad[1]; 5419 ++Quad[2]; 5420 ++Quad[3]; 5421 continue; 5422 } 5423 ++Quad[EltIdx / 4]; 5424 InputQuads.set(EltIdx / 4); 5425 } 5426 5427 int BestLoQuad = -1; 5428 unsigned MaxQuad = 1; 5429 for (unsigned i = 0; i < 4; ++i) { 5430 if (LoQuad[i] > MaxQuad) { 5431 BestLoQuad = i; 5432 MaxQuad = LoQuad[i]; 5433 } 5434 } 5435 5436 int BestHiQuad = -1; 5437 MaxQuad = 1; 5438 for (unsigned i = 0; i < 4; ++i) { 5439 if (HiQuad[i] > MaxQuad) { 5440 BestHiQuad = i; 5441 MaxQuad = HiQuad[i]; 5442 } 5443 } 5444 5445 // For SSSE3, If all 8 words of the result come from only 1 quadword of each 5446 // of the two input vectors, shuffle them into one input vector so only a 5447 // single pshufb instruction is necessary. If There are more than 2 input 5448 // quads, disable the next transformation since it does not help SSSE3. 5449 bool V1Used = InputQuads[0] || InputQuads[1]; 5450 bool V2Used = InputQuads[2] || InputQuads[3]; 5451 if (Subtarget->hasSSSE3()) { 5452 if (InputQuads.count() == 2 && V1Used && V2Used) { 5453 BestLoQuad = InputQuads.find_first(); 5454 BestHiQuad = InputQuads.find_next(BestLoQuad); 5455 } 5456 if (InputQuads.count() > 2) { 5457 BestLoQuad = -1; 5458 BestHiQuad = -1; 5459 } 5460 } 5461 5462 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update 5463 // the shuffle mask. If a quad is scored as -1, that means that it contains 5464 // words from all 4 input quadwords. 5465 SDValue NewV; 5466 if (BestLoQuad >= 0 || BestHiQuad >= 0) { 5467 SmallVector<int, 8> MaskV; 5468 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad); 5469 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad); 5470 NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 5471 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1), 5472 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]); 5473 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV); 5474 5475 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the 5476 // source words for the shuffle, to aid later transformations. 5477 bool AllWordsInNewV = true; 5478 bool InOrder[2] = { true, true }; 5479 for (unsigned i = 0; i != 8; ++i) { 5480 int idx = MaskVals[i]; 5481 if (idx != (int)i) 5482 InOrder[i/4] = false; 5483 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad) 5484 continue; 5485 AllWordsInNewV = false; 5486 break; 5487 } 5488 5489 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV; 5490 if (AllWordsInNewV) { 5491 for (int i = 0; i != 8; ++i) { 5492 int idx = MaskVals[i]; 5493 if (idx < 0) 5494 continue; 5495 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 5496 if ((idx != i) && idx < 4) 5497 pshufhw = false; 5498 if ((idx != i) && idx > 3) 5499 pshuflw = false; 5500 } 5501 V1 = NewV; 5502 V2Used = false; 5503 BestLoQuad = 0; 5504 BestHiQuad = 1; 5505 } 5506 5507 // If we've eliminated the use of V2, and the new mask is a pshuflw or 5508 // pshufhw, that's as cheap as it gets. Return the new shuffle. 5509 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) { 5510 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW; 5511 unsigned TargetMask = 0; 5512 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 5513 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]); 5514 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()): 5515 X86::getShufflePSHUFLWImmediate(NewV.getNode()); 5516 V1 = NewV.getOperand(0); 5517 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG); 5518 } 5519 } 5520 5521 // If we have SSSE3, and all words of the result are from 1 input vector, 5522 // case 2 is generated, otherwise case 3 is generated. If no SSSE3 5523 // is present, fall back to case 4. 5524 if (Subtarget->hasSSSE3()) { 5525 SmallVector<SDValue,16> pshufbMask; 5526 5527 // If we have elements from both input vectors, set the high bit of the 5528 // shuffle mask element to zero out elements that come from V2 in the V1 5529 // mask, and elements that come from V1 in the V2 mask, so that the two 5530 // results can be OR'd together. 5531 bool TwoInputs = V1Used && V2Used; 5532 for (unsigned i = 0; i != 8; ++i) { 5533 int EltIdx = MaskVals[i] * 2; 5534 if (TwoInputs && (EltIdx >= 16)) { 5535 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5536 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5537 continue; 5538 } 5539 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5540 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8)); 5541 } 5542 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1); 5543 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5544 DAG.getNode(ISD::BUILD_VECTOR, dl, 5545 MVT::v16i8, &pshufbMask[0], 16)); 5546 if (!TwoInputs) 5547 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5548 5549 // Calculate the shuffle mask for the second input, shuffle it, and 5550 // OR it with the first shuffled input. 5551 pshufbMask.clear(); 5552 for (unsigned i = 0; i != 8; ++i) { 5553 int EltIdx = MaskVals[i] * 2; 5554 if (EltIdx < 16) { 5555 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5556 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5557 continue; 5558 } 5559 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 5560 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8)); 5561 } 5562 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2); 5563 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5564 DAG.getNode(ISD::BUILD_VECTOR, dl, 5565 MVT::v16i8, &pshufbMask[0], 16)); 5566 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5567 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5568 } 5569 5570 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order, 5571 // and update MaskVals with new element order. 5572 BitVector InOrder(8); 5573 if (BestLoQuad >= 0) { 5574 SmallVector<int, 8> MaskV; 5575 for (int i = 0; i != 4; ++i) { 5576 int idx = MaskVals[i]; 5577 if (idx < 0) { 5578 MaskV.push_back(-1); 5579 InOrder.set(i); 5580 } else if ((idx / 4) == BestLoQuad) { 5581 MaskV.push_back(idx & 3); 5582 InOrder.set(i); 5583 } else { 5584 MaskV.push_back(-1); 5585 } 5586 } 5587 for (unsigned i = 4; i != 8; ++i) 5588 MaskV.push_back(i); 5589 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5590 &MaskV[0]); 5591 5592 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) 5593 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16, 5594 NewV.getOperand(0), 5595 X86::getShufflePSHUFLWImmediate(NewV.getNode()), 5596 DAG); 5597 } 5598 5599 // If BestHi >= 0, generate a pshufhw to put the high elements in order, 5600 // and update MaskVals with the new element order. 5601 if (BestHiQuad >= 0) { 5602 SmallVector<int, 8> MaskV; 5603 for (unsigned i = 0; i != 4; ++i) 5604 MaskV.push_back(i); 5605 for (unsigned i = 4; i != 8; ++i) { 5606 int idx = MaskVals[i]; 5607 if (idx < 0) { 5608 MaskV.push_back(-1); 5609 InOrder.set(i); 5610 } else if ((idx / 4) == BestHiQuad) { 5611 MaskV.push_back((idx & 3) + 4); 5612 InOrder.set(i); 5613 } else { 5614 MaskV.push_back(-1); 5615 } 5616 } 5617 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5618 &MaskV[0]); 5619 5620 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) 5621 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16, 5622 NewV.getOperand(0), 5623 X86::getShufflePSHUFHWImmediate(NewV.getNode()), 5624 DAG); 5625 } 5626 5627 // In case BestHi & BestLo were both -1, which means each quadword has a word 5628 // from each of the four input quadwords, calculate the InOrder bitvector now 5629 // before falling through to the insert/extract cleanup. 5630 if (BestLoQuad == -1 && BestHiQuad == -1) { 5631 NewV = V1; 5632 for (int i = 0; i != 8; ++i) 5633 if (MaskVals[i] < 0 || MaskVals[i] == i) 5634 InOrder.set(i); 5635 } 5636 5637 // The other elements are put in the right place using pextrw and pinsrw. 5638 for (unsigned i = 0; i != 8; ++i) { 5639 if (InOrder[i]) 5640 continue; 5641 int EltIdx = MaskVals[i]; 5642 if (EltIdx < 0) 5643 continue; 5644 SDValue ExtOp = (EltIdx < 8) 5645 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1, 5646 DAG.getIntPtrConstant(EltIdx)) 5647 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2, 5648 DAG.getIntPtrConstant(EltIdx - 8)); 5649 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp, 5650 DAG.getIntPtrConstant(i)); 5651 } 5652 return NewV; 5653} 5654 5655// v16i8 shuffles - Prefer shuffles in the following order: 5656// 1. [ssse3] 1 x pshufb 5657// 2. [ssse3] 2 x pshufb + 1 x por 5658// 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw 5659static 5660SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp, 5661 SelectionDAG &DAG, 5662 const X86TargetLowering &TLI) { 5663 SDValue V1 = SVOp->getOperand(0); 5664 SDValue V2 = SVOp->getOperand(1); 5665 DebugLoc dl = SVOp->getDebugLoc(); 5666 SmallVector<int, 16> MaskVals; 5667 SVOp->getMask(MaskVals); 5668 5669 // If we have SSSE3, case 1 is generated when all result bytes come from 5670 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is 5671 // present, fall back to case 3. 5672 // FIXME: kill V2Only once shuffles are canonizalized by getNode. 5673 bool V1Only = true; 5674 bool V2Only = true; 5675 for (unsigned i = 0; i < 16; ++i) { 5676 int EltIdx = MaskVals[i]; 5677 if (EltIdx < 0) 5678 continue; 5679 if (EltIdx < 16) 5680 V2Only = false; 5681 else 5682 V1Only = false; 5683 } 5684 5685 // If SSSE3, use 1 pshufb instruction per vector with elements in the result. 5686 if (TLI.getSubtarget()->hasSSSE3()) { 5687 SmallVector<SDValue,16> pshufbMask; 5688 5689 // If all result elements are from one input vector, then only translate 5690 // undef mask values to 0x80 (zero out result) in the pshufb mask. 5691 // 5692 // Otherwise, we have elements from both input vectors, and must zero out 5693 // elements that come from V2 in the first mask, and V1 in the second mask 5694 // so that we can OR them together. 5695 bool TwoInputs = !(V1Only || V2Only); 5696 for (unsigned i = 0; i != 16; ++i) { 5697 int EltIdx = MaskVals[i]; 5698 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) { 5699 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5700 continue; 5701 } 5702 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5703 } 5704 // If all the elements are from V2, assign it to V1 and return after 5705 // building the first pshufb. 5706 if (V2Only) 5707 V1 = V2; 5708 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5709 DAG.getNode(ISD::BUILD_VECTOR, dl, 5710 MVT::v16i8, &pshufbMask[0], 16)); 5711 if (!TwoInputs) 5712 return V1; 5713 5714 // Calculate the shuffle mask for the second input, shuffle it, and 5715 // OR it with the first shuffled input. 5716 pshufbMask.clear(); 5717 for (unsigned i = 0; i != 16; ++i) { 5718 int EltIdx = MaskVals[i]; 5719 if (EltIdx < 16) { 5720 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5721 continue; 5722 } 5723 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 5724 } 5725 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5726 DAG.getNode(ISD::BUILD_VECTOR, dl, 5727 MVT::v16i8, &pshufbMask[0], 16)); 5728 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5729 } 5730 5731 // No SSSE3 - Calculate in place words and then fix all out of place words 5732 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from 5733 // the 16 different words that comprise the two doublequadword input vectors. 5734 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5735 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 5736 SDValue NewV = V2Only ? V2 : V1; 5737 for (int i = 0; i != 8; ++i) { 5738 int Elt0 = MaskVals[i*2]; 5739 int Elt1 = MaskVals[i*2+1]; 5740 5741 // This word of the result is all undef, skip it. 5742 if (Elt0 < 0 && Elt1 < 0) 5743 continue; 5744 5745 // This word of the result is already in the correct place, skip it. 5746 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1)) 5747 continue; 5748 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17)) 5749 continue; 5750 5751 SDValue Elt0Src = Elt0 < 16 ? V1 : V2; 5752 SDValue Elt1Src = Elt1 < 16 ? V1 : V2; 5753 SDValue InsElt; 5754 5755 // If Elt0 and Elt1 are defined, are consecutive, and can be load 5756 // using a single extract together, load it and store it. 5757 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) { 5758 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5759 DAG.getIntPtrConstant(Elt1 / 2)); 5760 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5761 DAG.getIntPtrConstant(i)); 5762 continue; 5763 } 5764 5765 // If Elt1 is defined, extract it from the appropriate source. If the 5766 // source byte is not also odd, shift the extracted word left 8 bits 5767 // otherwise clear the bottom 8 bits if we need to do an or. 5768 if (Elt1 >= 0) { 5769 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5770 DAG.getIntPtrConstant(Elt1 / 2)); 5771 if ((Elt1 & 1) == 0) 5772 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt, 5773 DAG.getConstant(8, 5774 TLI.getShiftAmountTy(InsElt.getValueType()))); 5775 else if (Elt0 >= 0) 5776 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt, 5777 DAG.getConstant(0xFF00, MVT::i16)); 5778 } 5779 // If Elt0 is defined, extract it from the appropriate source. If the 5780 // source byte is not also even, shift the extracted word right 8 bits. If 5781 // Elt1 was also defined, OR the extracted values together before 5782 // inserting them in the result. 5783 if (Elt0 >= 0) { 5784 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, 5785 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2)); 5786 if ((Elt0 & 1) != 0) 5787 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0, 5788 DAG.getConstant(8, 5789 TLI.getShiftAmountTy(InsElt0.getValueType()))); 5790 else if (Elt1 >= 0) 5791 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0, 5792 DAG.getConstant(0x00FF, MVT::i16)); 5793 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0) 5794 : InsElt0; 5795 } 5796 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5797 DAG.getIntPtrConstant(i)); 5798 } 5799 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV); 5800} 5801 5802/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide 5803/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be 5804/// done when every pair / quad of shuffle mask elements point to elements in 5805/// the right sequence. e.g. 5806/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15> 5807static 5808SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp, 5809 SelectionDAG &DAG, DebugLoc dl) { 5810 EVT VT = SVOp->getValueType(0); 5811 SDValue V1 = SVOp->getOperand(0); 5812 SDValue V2 = SVOp->getOperand(1); 5813 unsigned NumElems = VT.getVectorNumElements(); 5814 unsigned NewWidth = (NumElems == 4) ? 2 : 4; 5815 EVT NewVT; 5816 switch (VT.getSimpleVT().SimpleTy) { 5817 default: assert(false && "Unexpected!"); 5818 case MVT::v4f32: NewVT = MVT::v2f64; break; 5819 case MVT::v4i32: NewVT = MVT::v2i64; break; 5820 case MVT::v8i16: NewVT = MVT::v4i32; break; 5821 case MVT::v16i8: NewVT = MVT::v4i32; break; 5822 } 5823 5824 int Scale = NumElems / NewWidth; 5825 SmallVector<int, 8> MaskVec; 5826 for (unsigned i = 0; i < NumElems; i += Scale) { 5827 int StartIdx = -1; 5828 for (int j = 0; j < Scale; ++j) { 5829 int EltIdx = SVOp->getMaskElt(i+j); 5830 if (EltIdx < 0) 5831 continue; 5832 if (StartIdx == -1) 5833 StartIdx = EltIdx - (EltIdx % Scale); 5834 if (EltIdx != StartIdx + j) 5835 return SDValue(); 5836 } 5837 if (StartIdx == -1) 5838 MaskVec.push_back(-1); 5839 else 5840 MaskVec.push_back(StartIdx / Scale); 5841 } 5842 5843 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1); 5844 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2); 5845 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]); 5846} 5847 5848/// getVZextMovL - Return a zero-extending vector move low node. 5849/// 5850static SDValue getVZextMovL(EVT VT, EVT OpVT, 5851 SDValue SrcOp, SelectionDAG &DAG, 5852 const X86Subtarget *Subtarget, DebugLoc dl) { 5853 if (VT == MVT::v2f64 || VT == MVT::v4f32) { 5854 LoadSDNode *LD = NULL; 5855 if (!isScalarLoadToVector(SrcOp.getNode(), &LD)) 5856 LD = dyn_cast<LoadSDNode>(SrcOp); 5857 if (!LD) { 5858 // movssrr and movsdrr do not clear top bits. Try to use movd, movq 5859 // instead. 5860 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32; 5861 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) && 5862 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 5863 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST && 5864 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) { 5865 // PR2108 5866 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32; 5867 return DAG.getNode(ISD::BITCAST, dl, VT, 5868 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 5869 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5870 OpVT, 5871 SrcOp.getOperand(0) 5872 .getOperand(0)))); 5873 } 5874 } 5875 } 5876 5877 return DAG.getNode(ISD::BITCAST, dl, VT, 5878 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 5879 DAG.getNode(ISD::BITCAST, dl, 5880 OpVT, SrcOp))); 5881} 5882 5883/// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector 5884/// shuffle node referes to only one lane in the sources. 5885static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) { 5886 EVT VT = SVOp->getValueType(0); 5887 int NumElems = VT.getVectorNumElements(); 5888 int HalfSize = NumElems/2; 5889 SmallVector<int, 16> M; 5890 SVOp->getMask(M); 5891 bool MatchA = false, MatchB = false; 5892 5893 for (int l = 0; l < NumElems*2; l += HalfSize) { 5894 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) { 5895 MatchA = true; 5896 break; 5897 } 5898 } 5899 5900 for (int l = 0; l < NumElems*2; l += HalfSize) { 5901 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) { 5902 MatchB = true; 5903 break; 5904 } 5905 } 5906 5907 return MatchA && MatchB; 5908} 5909 5910/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles 5911/// which could not be matched by any known target speficic shuffle 5912static SDValue 5913LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 5914 if (areShuffleHalvesWithinDisjointLanes(SVOp)) { 5915 // If each half of a vector shuffle node referes to only one lane in the 5916 // source vectors, extract each used 128-bit lane and shuffle them using 5917 // 128-bit shuffles. Then, concatenate the results. Otherwise leave 5918 // the work to the legalizer. 5919 DebugLoc dl = SVOp->getDebugLoc(); 5920 EVT VT = SVOp->getValueType(0); 5921 int NumElems = VT.getVectorNumElements(); 5922 int HalfSize = NumElems/2; 5923 5924 // Extract the reference for each half 5925 int FstVecExtractIdx = 0, SndVecExtractIdx = 0; 5926 int FstVecOpNum = 0, SndVecOpNum = 0; 5927 for (int i = 0; i < HalfSize; ++i) { 5928 int Elt = SVOp->getMaskElt(i); 5929 if (SVOp->getMaskElt(i) < 0) 5930 continue; 5931 FstVecOpNum = Elt/NumElems; 5932 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize; 5933 break; 5934 } 5935 for (int i = HalfSize; i < NumElems; ++i) { 5936 int Elt = SVOp->getMaskElt(i); 5937 if (SVOp->getMaskElt(i) < 0) 5938 continue; 5939 SndVecOpNum = Elt/NumElems; 5940 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize; 5941 break; 5942 } 5943 5944 // Extract the subvectors 5945 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum), 5946 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl); 5947 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum), 5948 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl); 5949 5950 // Generate 128-bit shuffles 5951 SmallVector<int, 16> MaskV1, MaskV2; 5952 for (int i = 0; i < HalfSize; ++i) { 5953 int Elt = SVOp->getMaskElt(i); 5954 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize); 5955 } 5956 for (int i = HalfSize; i < NumElems; ++i) { 5957 int Elt = SVOp->getMaskElt(i); 5958 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize); 5959 } 5960 5961 EVT NVT = V1.getValueType(); 5962 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]); 5963 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]); 5964 5965 // Concatenate the result back 5966 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1, 5967 DAG.getConstant(0, MVT::i32), DAG, dl); 5968 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32), 5969 DAG, dl); 5970 } 5971 5972 return SDValue(); 5973} 5974 5975/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with 5976/// 4 elements, and match them with several different shuffle types. 5977static SDValue 5978LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 5979 SDValue V1 = SVOp->getOperand(0); 5980 SDValue V2 = SVOp->getOperand(1); 5981 DebugLoc dl = SVOp->getDebugLoc(); 5982 EVT VT = SVOp->getValueType(0); 5983 5984 assert(VT.getSizeInBits() == 128 && "Unsupported vector size"); 5985 5986 SmallVector<std::pair<int, int>, 8> Locs; 5987 Locs.resize(4); 5988 SmallVector<int, 8> Mask1(4U, -1); 5989 SmallVector<int, 8> PermMask; 5990 SVOp->getMask(PermMask); 5991 5992 unsigned NumHi = 0; 5993 unsigned NumLo = 0; 5994 for (unsigned i = 0; i != 4; ++i) { 5995 int Idx = PermMask[i]; 5996 if (Idx < 0) { 5997 Locs[i] = std::make_pair(-1, -1); 5998 } else { 5999 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!"); 6000 if (Idx < 4) { 6001 Locs[i] = std::make_pair(0, NumLo); 6002 Mask1[NumLo] = Idx; 6003 NumLo++; 6004 } else { 6005 Locs[i] = std::make_pair(1, NumHi); 6006 if (2+NumHi < 4) 6007 Mask1[2+NumHi] = Idx; 6008 NumHi++; 6009 } 6010 } 6011 } 6012 6013 if (NumLo <= 2 && NumHi <= 2) { 6014 // If no more than two elements come from either vector. This can be 6015 // implemented with two shuffles. First shuffle gather the elements. 6016 // The second shuffle, which takes the first shuffle as both of its 6017 // vector operands, put the elements into the right order. 6018 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6019 6020 SmallVector<int, 8> Mask2(4U, -1); 6021 6022 for (unsigned i = 0; i != 4; ++i) { 6023 if (Locs[i].first == -1) 6024 continue; 6025 else { 6026 unsigned Idx = (i < 2) ? 0 : 4; 6027 Idx += Locs[i].first * 2 + Locs[i].second; 6028 Mask2[i] = Idx; 6029 } 6030 } 6031 6032 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]); 6033 } else if (NumLo == 3 || NumHi == 3) { 6034 // Otherwise, we must have three elements from one vector, call it X, and 6035 // one element from the other, call it Y. First, use a shufps to build an 6036 // intermediate vector with the one element from Y and the element from X 6037 // that will be in the same half in the final destination (the indexes don't 6038 // matter). Then, use a shufps to build the final vector, taking the half 6039 // containing the element from Y from the intermediate, and the other half 6040 // from X. 6041 if (NumHi == 3) { 6042 // Normalize it so the 3 elements come from V1. 6043 CommuteVectorShuffleMask(PermMask, VT); 6044 std::swap(V1, V2); 6045 } 6046 6047 // Find the element from V2. 6048 unsigned HiIndex; 6049 for (HiIndex = 0; HiIndex < 3; ++HiIndex) { 6050 int Val = PermMask[HiIndex]; 6051 if (Val < 0) 6052 continue; 6053 if (Val >= 4) 6054 break; 6055 } 6056 6057 Mask1[0] = PermMask[HiIndex]; 6058 Mask1[1] = -1; 6059 Mask1[2] = PermMask[HiIndex^1]; 6060 Mask1[3] = -1; 6061 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6062 6063 if (HiIndex >= 2) { 6064 Mask1[0] = PermMask[0]; 6065 Mask1[1] = PermMask[1]; 6066 Mask1[2] = HiIndex & 1 ? 6 : 4; 6067 Mask1[3] = HiIndex & 1 ? 4 : 6; 6068 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6069 } else { 6070 Mask1[0] = HiIndex & 1 ? 2 : 0; 6071 Mask1[1] = HiIndex & 1 ? 0 : 2; 6072 Mask1[2] = PermMask[2]; 6073 Mask1[3] = PermMask[3]; 6074 if (Mask1[2] >= 0) 6075 Mask1[2] += 4; 6076 if (Mask1[3] >= 0) 6077 Mask1[3] += 4; 6078 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]); 6079 } 6080 } 6081 6082 // Break it into (shuffle shuffle_hi, shuffle_lo). 6083 Locs.clear(); 6084 Locs.resize(4); 6085 SmallVector<int,8> LoMask(4U, -1); 6086 SmallVector<int,8> HiMask(4U, -1); 6087 6088 SmallVector<int,8> *MaskPtr = &LoMask; 6089 unsigned MaskIdx = 0; 6090 unsigned LoIdx = 0; 6091 unsigned HiIdx = 2; 6092 for (unsigned i = 0; i != 4; ++i) { 6093 if (i == 2) { 6094 MaskPtr = &HiMask; 6095 MaskIdx = 1; 6096 LoIdx = 0; 6097 HiIdx = 2; 6098 } 6099 int Idx = PermMask[i]; 6100 if (Idx < 0) { 6101 Locs[i] = std::make_pair(-1, -1); 6102 } else if (Idx < 4) { 6103 Locs[i] = std::make_pair(MaskIdx, LoIdx); 6104 (*MaskPtr)[LoIdx] = Idx; 6105 LoIdx++; 6106 } else { 6107 Locs[i] = std::make_pair(MaskIdx, HiIdx); 6108 (*MaskPtr)[HiIdx] = Idx; 6109 HiIdx++; 6110 } 6111 } 6112 6113 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]); 6114 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]); 6115 SmallVector<int, 8> MaskOps; 6116 for (unsigned i = 0; i != 4; ++i) { 6117 if (Locs[i].first == -1) { 6118 MaskOps.push_back(-1); 6119 } else { 6120 unsigned Idx = Locs[i].first * 4 + Locs[i].second; 6121 MaskOps.push_back(Idx); 6122 } 6123 } 6124 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]); 6125} 6126 6127static bool MayFoldVectorLoad(SDValue V) { 6128 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6129 V = V.getOperand(0); 6130 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6131 V = V.getOperand(0); 6132 if (MayFoldLoad(V)) 6133 return true; 6134 return false; 6135} 6136 6137// FIXME: the version above should always be used. Since there's 6138// a bug where several vector shuffles can't be folded because the 6139// DAG is not updated during lowering and a node claims to have two 6140// uses while it only has one, use this version, and let isel match 6141// another instruction if the load really happens to have more than 6142// one use. Remove this version after this bug get fixed. 6143// rdar://8434668, PR8156 6144static bool RelaxedMayFoldVectorLoad(SDValue V) { 6145 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6146 V = V.getOperand(0); 6147 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6148 V = V.getOperand(0); 6149 if (ISD::isNormalLoad(V.getNode())) 6150 return true; 6151 return false; 6152} 6153 6154/// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by 6155/// a vector extract, and if both can be later optimized into a single load. 6156/// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked 6157/// here because otherwise a target specific shuffle node is going to be 6158/// emitted for this shuffle, and the optimization not done. 6159/// FIXME: This is probably not the best approach, but fix the problem 6160/// until the right path is decided. 6161static 6162bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG, 6163 const TargetLowering &TLI) { 6164 EVT VT = V.getValueType(); 6165 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V); 6166 6167 // Be sure that the vector shuffle is present in a pattern like this: 6168 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr) 6169 if (!V.hasOneUse()) 6170 return false; 6171 6172 SDNode *N = *V.getNode()->use_begin(); 6173 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 6174 return false; 6175 6176 SDValue EltNo = N->getOperand(1); 6177 if (!isa<ConstantSDNode>(EltNo)) 6178 return false; 6179 6180 // If the bit convert changed the number of elements, it is unsafe 6181 // to examine the mask. 6182 bool HasShuffleIntoBitcast = false; 6183 if (V.getOpcode() == ISD::BITCAST) { 6184 EVT SrcVT = V.getOperand(0).getValueType(); 6185 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements()) 6186 return false; 6187 V = V.getOperand(0); 6188 HasShuffleIntoBitcast = true; 6189 } 6190 6191 // Select the input vector, guarding against out of range extract vector. 6192 unsigned NumElems = VT.getVectorNumElements(); 6193 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6194 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt); 6195 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1); 6196 6197 // Skip one more bit_convert if necessary 6198 if (V.getOpcode() == ISD::BITCAST) 6199 V = V.getOperand(0); 6200 6201 if (ISD::isNormalLoad(V.getNode())) { 6202 // Is the original load suitable? 6203 LoadSDNode *LN0 = cast<LoadSDNode>(V); 6204 6205 // FIXME: avoid the multi-use bug that is preventing lots of 6206 // of foldings to be detected, this is still wrong of course, but 6207 // give the temporary desired behavior, and if it happens that 6208 // the load has real more uses, during isel it will not fold, and 6209 // will generate poor code. 6210 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse() 6211 return false; 6212 6213 if (!HasShuffleIntoBitcast) 6214 return true; 6215 6216 // If there's a bitcast before the shuffle, check if the load type and 6217 // alignment is valid. 6218 unsigned Align = LN0->getAlignment(); 6219 unsigned NewAlign = 6220 TLI.getTargetData()->getABITypeAlignment( 6221 VT.getTypeForEVT(*DAG.getContext())); 6222 6223 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT)) 6224 return false; 6225 } 6226 6227 return true; 6228} 6229 6230static 6231SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) { 6232 EVT VT = Op.getValueType(); 6233 6234 // Canonizalize to v2f64. 6235 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 6236 return DAG.getNode(ISD::BITCAST, dl, VT, 6237 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64, 6238 V1, DAG)); 6239} 6240 6241static 6242SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, 6243 bool HasSSE2) { 6244 SDValue V1 = Op.getOperand(0); 6245 SDValue V2 = Op.getOperand(1); 6246 EVT VT = Op.getValueType(); 6247 6248 assert(VT != MVT::v2i64 && "unsupported shuffle type"); 6249 6250 if (HasSSE2 && VT == MVT::v2f64) 6251 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG); 6252 6253 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1) 6254 return DAG.getNode(ISD::BITCAST, dl, VT, 6255 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32, 6256 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1), 6257 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG)); 6258} 6259 6260static 6261SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) { 6262 SDValue V1 = Op.getOperand(0); 6263 SDValue V2 = Op.getOperand(1); 6264 EVT VT = Op.getValueType(); 6265 6266 assert((VT == MVT::v4i32 || VT == MVT::v4f32) && 6267 "unsupported shuffle type"); 6268 6269 if (V2.getOpcode() == ISD::UNDEF) 6270 V2 = V1; 6271 6272 // v4i32 or v4f32 6273 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG); 6274} 6275 6276static inline unsigned getSHUFPOpcode(EVT VT) { 6277 switch(VT.getSimpleVT().SimpleTy) { 6278 case MVT::v8i32: // Use fp unit for int unpack. 6279 case MVT::v8f32: 6280 case MVT::v4i32: // Use fp unit for int unpack. 6281 case MVT::v4f32: return X86ISD::SHUFPS; 6282 case MVT::v4i64: // Use fp unit for int unpack. 6283 case MVT::v4f64: 6284 case MVT::v2i64: // Use fp unit for int unpack. 6285 case MVT::v2f64: return X86ISD::SHUFPD; 6286 default: 6287 llvm_unreachable("Unknown type for shufp*"); 6288 } 6289 return 0; 6290} 6291 6292static 6293SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) { 6294 SDValue V1 = Op.getOperand(0); 6295 SDValue V2 = Op.getOperand(1); 6296 EVT VT = Op.getValueType(); 6297 unsigned NumElems = VT.getVectorNumElements(); 6298 6299 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second 6300 // operand of these instructions is only memory, so check if there's a 6301 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the 6302 // same masks. 6303 bool CanFoldLoad = false; 6304 6305 // Trivial case, when V2 comes from a load. 6306 if (MayFoldVectorLoad(V2)) 6307 CanFoldLoad = true; 6308 6309 // When V1 is a load, it can be folded later into a store in isel, example: 6310 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1) 6311 // turns into: 6312 // (MOVLPSmr addr:$src1, VR128:$src2) 6313 // So, recognize this potential and also use MOVLPS or MOVLPD 6314 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op)) 6315 CanFoldLoad = true; 6316 6317 // Both of them can't be memory operations though. 6318 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2)) 6319 CanFoldLoad = false; 6320 6321 if (CanFoldLoad) { 6322 if (HasSSE2 && NumElems == 2) 6323 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG); 6324 6325 if (NumElems == 4) 6326 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG); 6327 } 6328 6329 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6330 // movl and movlp will both match v2i64, but v2i64 is never matched by 6331 // movl earlier because we make it strict to avoid messing with the movlp load 6332 // folding logic (see the code above getMOVLP call). Match it here then, 6333 // this is horrible, but will stay like this until we move all shuffle 6334 // matching to x86 specific nodes. Note that for the 1st condition all 6335 // types are matched with movsd. 6336 if (HasSSE2) { 6337 if (NumElems == 2) 6338 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6339 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6340 } 6341 6342 assert(VT != MVT::v4i32 && "unsupported shuffle type"); 6343 6344 // Invert the operand order and use SHUFPS to match it. 6345 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1, 6346 X86::getShuffleSHUFImmediate(SVOp), DAG); 6347} 6348 6349static inline unsigned getUNPCKLOpcode(EVT VT) { 6350 switch(VT.getSimpleVT().SimpleTy) { 6351 case MVT::v4i32: return X86ISD::PUNPCKLDQ; 6352 case MVT::v2i64: return X86ISD::PUNPCKLQDQ; 6353 case MVT::v4f32: return X86ISD::UNPCKLPS; 6354 case MVT::v2f64: return X86ISD::UNPCKLPD; 6355 case MVT::v8i32: // Use fp unit for int unpack. 6356 case MVT::v8f32: return X86ISD::VUNPCKLPSY; 6357 case MVT::v4i64: // Use fp unit for int unpack. 6358 case MVT::v4f64: return X86ISD::VUNPCKLPDY; 6359 case MVT::v16i8: return X86ISD::PUNPCKLBW; 6360 case MVT::v8i16: return X86ISD::PUNPCKLWD; 6361 default: 6362 llvm_unreachable("Unknown type for unpckl"); 6363 } 6364 return 0; 6365} 6366 6367static inline unsigned getUNPCKHOpcode(EVT VT) { 6368 switch(VT.getSimpleVT().SimpleTy) { 6369 case MVT::v4i32: return X86ISD::PUNPCKHDQ; 6370 case MVT::v2i64: return X86ISD::PUNPCKHQDQ; 6371 case MVT::v4f32: return X86ISD::UNPCKHPS; 6372 case MVT::v2f64: return X86ISD::UNPCKHPD; 6373 case MVT::v8i32: // Use fp unit for int unpack. 6374 case MVT::v8f32: return X86ISD::VUNPCKHPSY; 6375 case MVT::v4i64: // Use fp unit for int unpack. 6376 case MVT::v4f64: return X86ISD::VUNPCKHPDY; 6377 case MVT::v16i8: return X86ISD::PUNPCKHBW; 6378 case MVT::v8i16: return X86ISD::PUNPCKHWD; 6379 default: 6380 llvm_unreachable("Unknown type for unpckh"); 6381 } 6382 return 0; 6383} 6384 6385static inline unsigned getVPERMILOpcode(EVT VT) { 6386 switch(VT.getSimpleVT().SimpleTy) { 6387 case MVT::v4i32: 6388 case MVT::v4f32: return X86ISD::VPERMILPS; 6389 case MVT::v2i64: 6390 case MVT::v2f64: return X86ISD::VPERMILPD; 6391 case MVT::v8i32: 6392 case MVT::v8f32: return X86ISD::VPERMILPSY; 6393 case MVT::v4i64: 6394 case MVT::v4f64: return X86ISD::VPERMILPDY; 6395 default: 6396 llvm_unreachable("Unknown type for vpermil"); 6397 } 6398 return 0; 6399} 6400 6401/// isVectorBroadcast - Check if the node chain is suitable to be xformed to 6402/// a vbroadcast node. The nodes are suitable whenever we can fold a load coming 6403/// from a 32 or 64 bit scalar. Update Op to the desired load to be folded. 6404static bool isVectorBroadcast(SDValue &Op) { 6405 EVT VT = Op.getValueType(); 6406 bool Is256 = VT.getSizeInBits() == 256; 6407 6408 assert((VT.getSizeInBits() == 128 || Is256) && 6409 "Unsupported type for vbroadcast node"); 6410 6411 SDValue V = Op; 6412 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6413 V = V.getOperand(0); 6414 6415 if (Is256 && !(V.hasOneUse() && 6416 V.getOpcode() == ISD::INSERT_SUBVECTOR && 6417 V.getOperand(0).getOpcode() == ISD::UNDEF)) 6418 return false; 6419 6420 if (Is256) 6421 V = V.getOperand(1); 6422 6423 if (!V.hasOneUse()) 6424 return false; 6425 6426 // Check the source scalar_to_vector type. 256-bit broadcasts are 6427 // supported for 32/64-bit sizes, while 128-bit ones are only supported 6428 // for 32-bit scalars. 6429 if (V.getOpcode() != ISD::SCALAR_TO_VECTOR) 6430 return false; 6431 6432 unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits(); 6433 if (ScalarSize != 32 && ScalarSize != 64) 6434 return false; 6435 if (!Is256 && ScalarSize == 64) 6436 return false; 6437 6438 V = V.getOperand(0); 6439 if (!MayFoldLoad(V)) 6440 return false; 6441 6442 // Return the load node 6443 Op = V; 6444 return true; 6445} 6446 6447static 6448SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG, 6449 const TargetLowering &TLI, 6450 const X86Subtarget *Subtarget) { 6451 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6452 EVT VT = Op.getValueType(); 6453 DebugLoc dl = Op.getDebugLoc(); 6454 SDValue V1 = Op.getOperand(0); 6455 SDValue V2 = Op.getOperand(1); 6456 6457 if (isZeroShuffle(SVOp)) 6458 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl); 6459 6460 // Handle splat operations 6461 if (SVOp->isSplat()) { 6462 unsigned NumElem = VT.getVectorNumElements(); 6463 int Size = VT.getSizeInBits(); 6464 // Special case, this is the only place now where it's allowed to return 6465 // a vector_shuffle operation without using a target specific node, because 6466 // *hopefully* it will be optimized away by the dag combiner. FIXME: should 6467 // this be moved to DAGCombine instead? 6468 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI)) 6469 return Op; 6470 6471 // Use vbroadcast whenever the splat comes from a foldable load 6472 if (Subtarget->hasAVX() && isVectorBroadcast(V1)) 6473 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1); 6474 6475 // Handle splats by matching through known shuffle masks 6476 if ((Size == 128 && NumElem <= 4) || 6477 (Size == 256 && NumElem < 8)) 6478 return SDValue(); 6479 6480 // All remaning splats are promoted to target supported vector shuffles. 6481 return PromoteSplat(SVOp, DAG); 6482 } 6483 6484 // If the shuffle can be profitably rewritten as a narrower shuffle, then 6485 // do it! 6486 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 6487 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6488 if (NewOp.getNode()) 6489 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp); 6490 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) { 6491 // FIXME: Figure out a cleaner way to do this. 6492 // Try to make use of movq to zero out the top part. 6493 if (ISD::isBuildVectorAllZeros(V2.getNode())) { 6494 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6495 if (NewOp.getNode()) { 6496 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false)) 6497 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0), 6498 DAG, Subtarget, dl); 6499 } 6500 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) { 6501 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6502 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp))) 6503 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1), 6504 DAG, Subtarget, dl); 6505 } 6506 } 6507 return SDValue(); 6508} 6509 6510SDValue 6511X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { 6512 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6513 SDValue V1 = Op.getOperand(0); 6514 SDValue V2 = Op.getOperand(1); 6515 EVT VT = Op.getValueType(); 6516 DebugLoc dl = Op.getDebugLoc(); 6517 unsigned NumElems = VT.getVectorNumElements(); 6518 bool isMMX = VT.getSizeInBits() == 64; 6519 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF; 6520 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 6521 bool V1IsSplat = false; 6522 bool V2IsSplat = false; 6523 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX(); 6524 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX(); 6525 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX(); 6526 MachineFunction &MF = DAG.getMachineFunction(); 6527 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize); 6528 6529 // Shuffle operations on MMX not supported. 6530 if (isMMX) 6531 return Op; 6532 6533 // Vector shuffle lowering takes 3 steps: 6534 // 6535 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable 6536 // narrowing and commutation of operands should be handled. 6537 // 2) Matching of shuffles with known shuffle masks to x86 target specific 6538 // shuffle nodes. 6539 // 3) Rewriting of unmatched masks into new generic shuffle operations, 6540 // so the shuffle can be broken into other shuffles and the legalizer can 6541 // try the lowering again. 6542 // 6543 // The general ideia is that no vector_shuffle operation should be left to 6544 // be matched during isel, all of them must be converted to a target specific 6545 // node here. 6546 6547 // Normalize the input vectors. Here splats, zeroed vectors, profitable 6548 // narrowing and commutation of operands should be handled. The actual code 6549 // doesn't include all of those, work in progress... 6550 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget); 6551 if (NewOp.getNode()) 6552 return NewOp; 6553 6554 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and 6555 // unpckh_undef). Only use pshufd if speed is more important than size. 6556 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp)) 6557 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG); 6558 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp)) 6559 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 6560 6561 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef && 6562 RelaxedMayFoldVectorLoad(V1)) 6563 return getMOVDDup(Op, dl, V1, DAG); 6564 6565 if (X86::isMOVHLPS_v_undef_Mask(SVOp)) 6566 return getMOVHighToLow(Op, dl, DAG); 6567 6568 // Use to match splats 6569 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef && 6570 (VT == MVT::v2f64 || VT == MVT::v2i64)) 6571 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 6572 6573 if (X86::isPSHUFDMask(SVOp)) { 6574 // The actual implementation will match the mask in the if above and then 6575 // during isel it can match several different instructions, not only pshufd 6576 // as its name says, sad but true, emulate the behavior for now... 6577 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64))) 6578 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG); 6579 6580 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp); 6581 6582 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32)) 6583 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG); 6584 6585 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1, 6586 TargetMask, DAG); 6587 } 6588 6589 // Check if this can be converted into a logical shift. 6590 bool isLeft = false; 6591 unsigned ShAmt = 0; 6592 SDValue ShVal; 6593 bool isShift = getSubtarget()->hasSSE2() && 6594 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt); 6595 if (isShift && ShVal.hasOneUse()) { 6596 // If the shifted value has multiple uses, it may be cheaper to use 6597 // v_set0 + movlhps or movhlps, etc. 6598 EVT EltVT = VT.getVectorElementType(); 6599 ShAmt *= EltVT.getSizeInBits(); 6600 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6601 } 6602 6603 if (X86::isMOVLMask(SVOp)) { 6604 if (V1IsUndef) 6605 return V2; 6606 if (ISD::isBuildVectorAllZeros(V1.getNode())) 6607 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl); 6608 if (!X86::isMOVLPMask(SVOp)) { 6609 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 6610 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6611 6612 if (VT == MVT::v4i32 || VT == MVT::v4f32) 6613 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6614 } 6615 } 6616 6617 // FIXME: fold these into legal mask. 6618 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp)) 6619 return getMOVLowToHigh(Op, dl, DAG, HasSSE2); 6620 6621 if (X86::isMOVHLPSMask(SVOp)) 6622 return getMOVHighToLow(Op, dl, DAG); 6623 6624 if (X86::isMOVSHDUPMask(SVOp, Subtarget)) 6625 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG); 6626 6627 if (X86::isMOVSLDUPMask(SVOp, Subtarget)) 6628 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG); 6629 6630 if (X86::isMOVLPMask(SVOp)) 6631 return getMOVLP(Op, dl, DAG, HasSSE2); 6632 6633 if (ShouldXformToMOVHLPS(SVOp) || 6634 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp)) 6635 return CommuteVectorShuffle(SVOp, DAG); 6636 6637 if (isShift) { 6638 // No better options. Use a vshl / vsrl. 6639 EVT EltVT = VT.getVectorElementType(); 6640 ShAmt *= EltVT.getSizeInBits(); 6641 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6642 } 6643 6644 bool Commuted = false; 6645 // FIXME: This should also accept a bitcast of a splat? Be careful, not 6646 // 1,1,1,1 -> v8i16 though. 6647 V1IsSplat = isSplatVector(V1.getNode()); 6648 V2IsSplat = isSplatVector(V2.getNode()); 6649 6650 // Canonicalize the splat or undef, if present, to be on the RHS. 6651 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) { 6652 Op = CommuteVectorShuffle(SVOp, DAG); 6653 SVOp = cast<ShuffleVectorSDNode>(Op); 6654 V1 = SVOp->getOperand(0); 6655 V2 = SVOp->getOperand(1); 6656 std::swap(V1IsSplat, V2IsSplat); 6657 std::swap(V1IsUndef, V2IsUndef); 6658 Commuted = true; 6659 } 6660 6661 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) { 6662 // Shuffling low element of v1 into undef, just return v1. 6663 if (V2IsUndef) 6664 return V1; 6665 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which 6666 // the instruction selector will not match, so get a canonical MOVL with 6667 // swapped operands to undo the commute. 6668 return getMOVL(DAG, dl, VT, V2, V1); 6669 } 6670 6671 if (X86::isUNPCKLMask(SVOp)) 6672 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG); 6673 6674 if (X86::isUNPCKHMask(SVOp)) 6675 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG); 6676 6677 if (V2IsSplat) { 6678 // Normalize mask so all entries that point to V2 points to its first 6679 // element then try to match unpck{h|l} again. If match, return a 6680 // new vector_shuffle with the corrected mask. 6681 SDValue NewMask = NormalizeMask(SVOp, DAG); 6682 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask); 6683 if (NSVOp != SVOp) { 6684 if (X86::isUNPCKLMask(NSVOp, true)) { 6685 return NewMask; 6686 } else if (X86::isUNPCKHMask(NSVOp, true)) { 6687 return NewMask; 6688 } 6689 } 6690 } 6691 6692 if (Commuted) { 6693 // Commute is back and try unpck* again. 6694 // FIXME: this seems wrong. 6695 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG); 6696 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp); 6697 6698 if (X86::isUNPCKLMask(NewSVOp)) 6699 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG); 6700 6701 if (X86::isUNPCKHMask(NewSVOp)) 6702 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG); 6703 } 6704 6705 // Normalize the node to match x86 shuffle ops if needed 6706 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp)) 6707 return CommuteVectorShuffle(SVOp, DAG); 6708 6709 // The checks below are all present in isShuffleMaskLegal, but they are 6710 // inlined here right now to enable us to directly emit target specific 6711 // nodes, and remove one by one until they don't return Op anymore. 6712 SmallVector<int, 16> M; 6713 SVOp->getMask(M); 6714 6715 if (isPALIGNRMask(M, VT, HasSSSE3)) 6716 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2, 6717 X86::getShufflePALIGNRImmediate(SVOp), 6718 DAG); 6719 6720 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) && 6721 SVOp->getSplatIndex() == 0 && V2IsUndef) { 6722 if (VT == MVT::v2f64) 6723 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG); 6724 if (VT == MVT::v2i64) 6725 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG); 6726 } 6727 6728 if (isPSHUFHWMask(M, VT)) 6729 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1, 6730 X86::getShufflePSHUFHWImmediate(SVOp), 6731 DAG); 6732 6733 if (isPSHUFLWMask(M, VT)) 6734 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1, 6735 X86::getShufflePSHUFLWImmediate(SVOp), 6736 DAG); 6737 6738 if (isSHUFPMask(M, VT)) 6739 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, 6740 X86::getShuffleSHUFImmediate(SVOp), DAG); 6741 6742 if (X86::isUNPCKL_v_undef_Mask(SVOp)) 6743 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG); 6744 if (X86::isUNPCKH_v_undef_Mask(SVOp)) 6745 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 6746 6747 //===--------------------------------------------------------------------===// 6748 // Generate target specific nodes for 128 or 256-bit shuffles only 6749 // supported in the AVX instruction set. 6750 // 6751 6752 // Handle VMOVDDUPY permutations 6753 if (isMOVDDUPYMask(SVOp, Subtarget)) 6754 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG); 6755 6756 // Handle VPERMILPS* permutations 6757 if (isVPERMILPSMask(M, VT, Subtarget)) 6758 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1, 6759 getShuffleVPERMILPSImmediate(SVOp), DAG); 6760 6761 // Handle VPERMILPD* permutations 6762 if (isVPERMILPDMask(M, VT, Subtarget)) 6763 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1, 6764 getShuffleVPERMILPDImmediate(SVOp), DAG); 6765 6766 // Handle VPERM2F128 permutations 6767 if (isVPERM2F128Mask(M, VT, Subtarget)) 6768 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2, 6769 getShuffleVPERM2F128Immediate(SVOp), DAG); 6770 6771 // Handle VSHUFPSY permutations 6772 if (isVSHUFPSYMask(M, VT, Subtarget)) 6773 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, 6774 getShuffleVSHUFPSYImmediate(SVOp), DAG); 6775 6776 // Handle VSHUFPDY permutations 6777 if (isVSHUFPDYMask(M, VT, Subtarget)) 6778 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, 6779 getShuffleVSHUFPDYImmediate(SVOp), DAG); 6780 6781 //===--------------------------------------------------------------------===// 6782 // Since no target specific shuffle was selected for this generic one, 6783 // lower it into other known shuffles. FIXME: this isn't true yet, but 6784 // this is the plan. 6785 // 6786 6787 // Handle v8i16 specifically since SSE can do byte extraction and insertion. 6788 if (VT == MVT::v8i16) { 6789 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG); 6790 if (NewOp.getNode()) 6791 return NewOp; 6792 } 6793 6794 if (VT == MVT::v16i8) { 6795 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this); 6796 if (NewOp.getNode()) 6797 return NewOp; 6798 } 6799 6800 // Handle all 128-bit wide vectors with 4 elements, and match them with 6801 // several different shuffle types. 6802 if (NumElems == 4 && VT.getSizeInBits() == 128) 6803 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG); 6804 6805 // Handle general 256-bit shuffles 6806 if (VT.is256BitVector()) 6807 return LowerVECTOR_SHUFFLE_256(SVOp, DAG); 6808 6809 return SDValue(); 6810} 6811 6812SDValue 6813X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, 6814 SelectionDAG &DAG) const { 6815 EVT VT = Op.getValueType(); 6816 DebugLoc dl = Op.getDebugLoc(); 6817 6818 if (Op.getOperand(0).getValueType().getSizeInBits() != 128) 6819 return SDValue(); 6820 6821 if (VT.getSizeInBits() == 8) { 6822 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, 6823 Op.getOperand(0), Op.getOperand(1)); 6824 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 6825 DAG.getValueType(VT)); 6826 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6827 } else if (VT.getSizeInBits() == 16) { 6828 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6829 // If Idx is 0, it's cheaper to do a move instead of a pextrw. 6830 if (Idx == 0) 6831 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 6832 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6833 DAG.getNode(ISD::BITCAST, dl, 6834 MVT::v4i32, 6835 Op.getOperand(0)), 6836 Op.getOperand(1))); 6837 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, 6838 Op.getOperand(0), Op.getOperand(1)); 6839 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 6840 DAG.getValueType(VT)); 6841 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6842 } else if (VT == MVT::f32) { 6843 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy 6844 // the result back to FR32 register. It's only worth matching if the 6845 // result has a single use which is a store or a bitcast to i32. And in 6846 // the case of a store, it's not worth it if the index is a constant 0, 6847 // because a MOVSSmr can be used instead, which is smaller and faster. 6848 if (!Op.hasOneUse()) 6849 return SDValue(); 6850 SDNode *User = *Op.getNode()->use_begin(); 6851 if ((User->getOpcode() != ISD::STORE || 6852 (isa<ConstantSDNode>(Op.getOperand(1)) && 6853 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) && 6854 (User->getOpcode() != ISD::BITCAST || 6855 User->getValueType(0) != MVT::i32)) 6856 return SDValue(); 6857 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6858 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, 6859 Op.getOperand(0)), 6860 Op.getOperand(1)); 6861 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract); 6862 } else if (VT == MVT::i32) { 6863 // ExtractPS works with constant index. 6864 if (isa<ConstantSDNode>(Op.getOperand(1))) 6865 return Op; 6866 } 6867 return SDValue(); 6868} 6869 6870 6871SDValue 6872X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6873 SelectionDAG &DAG) const { 6874 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6875 return SDValue(); 6876 6877 SDValue Vec = Op.getOperand(0); 6878 EVT VecVT = Vec.getValueType(); 6879 6880 // If this is a 256-bit vector result, first extract the 128-bit vector and 6881 // then extract the element from the 128-bit vector. 6882 if (VecVT.getSizeInBits() == 256) { 6883 DebugLoc dl = Op.getNode()->getDebugLoc(); 6884 unsigned NumElems = VecVT.getVectorNumElements(); 6885 SDValue Idx = Op.getOperand(1); 6886 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 6887 6888 // Get the 128-bit vector. 6889 bool Upper = IdxVal >= NumElems/2; 6890 Vec = Extract128BitVector(Vec, 6891 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl); 6892 6893 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec, 6894 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx); 6895 } 6896 6897 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length"); 6898 6899 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) { 6900 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG); 6901 if (Res.getNode()) 6902 return Res; 6903 } 6904 6905 EVT VT = Op.getValueType(); 6906 DebugLoc dl = Op.getDebugLoc(); 6907 // TODO: handle v16i8. 6908 if (VT.getSizeInBits() == 16) { 6909 SDValue Vec = Op.getOperand(0); 6910 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6911 if (Idx == 0) 6912 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 6913 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6914 DAG.getNode(ISD::BITCAST, dl, 6915 MVT::v4i32, Vec), 6916 Op.getOperand(1))); 6917 // Transform it so it match pextrw which produces a 32-bit result. 6918 EVT EltVT = MVT::i32; 6919 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, 6920 Op.getOperand(0), Op.getOperand(1)); 6921 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract, 6922 DAG.getValueType(VT)); 6923 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6924 } else if (VT.getSizeInBits() == 32) { 6925 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6926 if (Idx == 0) 6927 return Op; 6928 6929 // SHUFPS the element to the lowest double word, then movss. 6930 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 }; 6931 EVT VVT = Op.getOperand(0).getValueType(); 6932 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 6933 DAG.getUNDEF(VVT), Mask); 6934 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 6935 DAG.getIntPtrConstant(0)); 6936 } else if (VT.getSizeInBits() == 64) { 6937 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b 6938 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught 6939 // to match extract_elt for f64. 6940 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6941 if (Idx == 0) 6942 return Op; 6943 6944 // UNPCKHPD the element to the lowest double word, then movsd. 6945 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored 6946 // to a f64mem, the whole operation is folded into a single MOVHPDmr. 6947 int Mask[2] = { 1, -1 }; 6948 EVT VVT = Op.getOperand(0).getValueType(); 6949 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 6950 DAG.getUNDEF(VVT), Mask); 6951 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 6952 DAG.getIntPtrConstant(0)); 6953 } 6954 6955 return SDValue(); 6956} 6957 6958SDValue 6959X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, 6960 SelectionDAG &DAG) const { 6961 EVT VT = Op.getValueType(); 6962 EVT EltVT = VT.getVectorElementType(); 6963 DebugLoc dl = Op.getDebugLoc(); 6964 6965 SDValue N0 = Op.getOperand(0); 6966 SDValue N1 = Op.getOperand(1); 6967 SDValue N2 = Op.getOperand(2); 6968 6969 if (VT.getSizeInBits() == 256) 6970 return SDValue(); 6971 6972 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) && 6973 isa<ConstantSDNode>(N2)) { 6974 unsigned Opc; 6975 if (VT == MVT::v8i16) 6976 Opc = X86ISD::PINSRW; 6977 else if (VT == MVT::v16i8) 6978 Opc = X86ISD::PINSRB; 6979 else 6980 Opc = X86ISD::PINSRB; 6981 6982 // Transform it so it match pinsr{b,w} which expects a GR32 as its second 6983 // argument. 6984 if (N1.getValueType() != MVT::i32) 6985 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 6986 if (N2.getValueType() != MVT::i32) 6987 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 6988 return DAG.getNode(Opc, dl, VT, N0, N1, N2); 6989 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) { 6990 // Bits [7:6] of the constant are the source select. This will always be 6991 // zero here. The DAG Combiner may combine an extract_elt index into these 6992 // bits. For example (insert (extract, 3), 2) could be matched by putting 6993 // the '3' into bits [7:6] of X86ISD::INSERTPS. 6994 // Bits [5:4] of the constant are the destination select. This is the 6995 // value of the incoming immediate. 6996 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may 6997 // combine either bitwise AND or insert of float 0.0 to set these bits. 6998 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4); 6999 // Create this as a scalar to vector.. 7000 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1); 7001 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2); 7002 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) { 7003 // PINSR* works with constant index. 7004 return Op; 7005 } 7006 return SDValue(); 7007} 7008 7009SDValue 7010X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 7011 EVT VT = Op.getValueType(); 7012 EVT EltVT = VT.getVectorElementType(); 7013 7014 DebugLoc dl = Op.getDebugLoc(); 7015 SDValue N0 = Op.getOperand(0); 7016 SDValue N1 = Op.getOperand(1); 7017 SDValue N2 = Op.getOperand(2); 7018 7019 // If this is a 256-bit vector result, first extract the 128-bit vector, 7020 // insert the element into the extracted half and then place it back. 7021 if (VT.getSizeInBits() == 256) { 7022 if (!isa<ConstantSDNode>(N2)) 7023 return SDValue(); 7024 7025 // Get the desired 128-bit vector half. 7026 unsigned NumElems = VT.getVectorNumElements(); 7027 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue(); 7028 bool Upper = IdxVal >= NumElems/2; 7029 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32); 7030 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl); 7031 7032 // Insert the element into the desired half. 7033 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, 7034 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2); 7035 7036 // Insert the changed part back to the 256-bit vector 7037 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl); 7038 } 7039 7040 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) 7041 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG); 7042 7043 if (EltVT == MVT::i8) 7044 return SDValue(); 7045 7046 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) { 7047 // Transform it so it match pinsrw which expects a 16-bit value in a GR32 7048 // as its second argument. 7049 if (N1.getValueType() != MVT::i32) 7050 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7051 if (N2.getValueType() != MVT::i32) 7052 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7053 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2); 7054 } 7055 return SDValue(); 7056} 7057 7058SDValue 7059X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const { 7060 LLVMContext *Context = DAG.getContext(); 7061 DebugLoc dl = Op.getDebugLoc(); 7062 EVT OpVT = Op.getValueType(); 7063 7064 // If this is a 256-bit vector result, first insert into a 128-bit 7065 // vector and then insert into the 256-bit vector. 7066 if (OpVT.getSizeInBits() > 128) { 7067 // Insert into a 128-bit vector. 7068 EVT VT128 = EVT::getVectorVT(*Context, 7069 OpVT.getVectorElementType(), 7070 OpVT.getVectorNumElements() / 2); 7071 7072 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0)); 7073 7074 // Insert the 128-bit vector. 7075 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op, 7076 DAG.getConstant(0, MVT::i32), 7077 DAG, dl); 7078 } 7079 7080 if (Op.getValueType() == MVT::v1i64 && 7081 Op.getOperand(0).getValueType() == MVT::i64) 7082 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0)); 7083 7084 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0)); 7085 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 && 7086 "Expected an SSE type!"); 7087 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), 7088 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt)); 7089} 7090 7091// Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in 7092// a simple subregister reference or explicit instructions to grab 7093// upper bits of a vector. 7094SDValue 7095X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 7096 if (Subtarget->hasAVX()) { 7097 DebugLoc dl = Op.getNode()->getDebugLoc(); 7098 SDValue Vec = Op.getNode()->getOperand(0); 7099 SDValue Idx = Op.getNode()->getOperand(1); 7100 7101 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 7102 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) { 7103 return Extract128BitVector(Vec, Idx, DAG, dl); 7104 } 7105 } 7106 return SDValue(); 7107} 7108 7109// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a 7110// simple superregister reference or explicit instructions to insert 7111// the upper bits of a vector. 7112SDValue 7113X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 7114 if (Subtarget->hasAVX()) { 7115 DebugLoc dl = Op.getNode()->getDebugLoc(); 7116 SDValue Vec = Op.getNode()->getOperand(0); 7117 SDValue SubVec = Op.getNode()->getOperand(1); 7118 SDValue Idx = Op.getNode()->getOperand(2); 7119 7120 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 7121 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) { 7122 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl); 7123 } 7124 } 7125 return SDValue(); 7126} 7127 7128// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 7129// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is 7130// one of the above mentioned nodes. It has to be wrapped because otherwise 7131// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 7132// be used to form addressing mode. These wrapped nodes will be selected 7133// into MOV32ri. 7134SDValue 7135X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { 7136 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 7137 7138 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7139 // global base reg. 7140 unsigned char OpFlag = 0; 7141 unsigned WrapperKind = X86ISD::Wrapper; 7142 CodeModel::Model M = getTargetMachine().getCodeModel(); 7143 7144 if (Subtarget->isPICStyleRIPRel() && 7145 (M == CodeModel::Small || M == CodeModel::Kernel)) 7146 WrapperKind = X86ISD::WrapperRIP; 7147 else if (Subtarget->isPICStyleGOT()) 7148 OpFlag = X86II::MO_GOTOFF; 7149 else if (Subtarget->isPICStyleStubPIC()) 7150 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7151 7152 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(), 7153 CP->getAlignment(), 7154 CP->getOffset(), OpFlag); 7155 DebugLoc DL = CP->getDebugLoc(); 7156 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7157 // With PIC, the address is actually $g + Offset. 7158 if (OpFlag) { 7159 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7160 DAG.getNode(X86ISD::GlobalBaseReg, 7161 DebugLoc(), getPointerTy()), 7162 Result); 7163 } 7164 7165 return Result; 7166} 7167 7168SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 7169 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 7170 7171 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7172 // global base reg. 7173 unsigned char OpFlag = 0; 7174 unsigned WrapperKind = X86ISD::Wrapper; 7175 CodeModel::Model M = getTargetMachine().getCodeModel(); 7176 7177 if (Subtarget->isPICStyleRIPRel() && 7178 (M == CodeModel::Small || M == CodeModel::Kernel)) 7179 WrapperKind = X86ISD::WrapperRIP; 7180 else if (Subtarget->isPICStyleGOT()) 7181 OpFlag = X86II::MO_GOTOFF; 7182 else if (Subtarget->isPICStyleStubPIC()) 7183 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7184 7185 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(), 7186 OpFlag); 7187 DebugLoc DL = JT->getDebugLoc(); 7188 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7189 7190 // With PIC, the address is actually $g + Offset. 7191 if (OpFlag) 7192 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7193 DAG.getNode(X86ISD::GlobalBaseReg, 7194 DebugLoc(), getPointerTy()), 7195 Result); 7196 7197 return Result; 7198} 7199 7200SDValue 7201X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { 7202 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 7203 7204 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7205 // global base reg. 7206 unsigned char OpFlag = 0; 7207 unsigned WrapperKind = X86ISD::Wrapper; 7208 CodeModel::Model M = getTargetMachine().getCodeModel(); 7209 7210 if (Subtarget->isPICStyleRIPRel() && 7211 (M == CodeModel::Small || M == CodeModel::Kernel)) { 7212 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF()) 7213 OpFlag = X86II::MO_GOTPCREL; 7214 WrapperKind = X86ISD::WrapperRIP; 7215 } else if (Subtarget->isPICStyleGOT()) { 7216 OpFlag = X86II::MO_GOT; 7217 } else if (Subtarget->isPICStyleStubPIC()) { 7218 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE; 7219 } else if (Subtarget->isPICStyleStubNoDynamic()) { 7220 OpFlag = X86II::MO_DARWIN_NONLAZY; 7221 } 7222 7223 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag); 7224 7225 DebugLoc DL = Op.getDebugLoc(); 7226 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7227 7228 7229 // With PIC, the address is actually $g + Offset. 7230 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 7231 !Subtarget->is64Bit()) { 7232 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7233 DAG.getNode(X86ISD::GlobalBaseReg, 7234 DebugLoc(), getPointerTy()), 7235 Result); 7236 } 7237 7238 // For symbols that require a load from a stub to get the address, emit the 7239 // load. 7240 if (isGlobalStubReference(OpFlag)) 7241 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result, 7242 MachinePointerInfo::getGOT(), false, false, 0); 7243 7244 return Result; 7245} 7246 7247SDValue 7248X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { 7249 // Create the TargetBlockAddressAddress node. 7250 unsigned char OpFlags = 7251 Subtarget->ClassifyBlockAddressReference(); 7252 CodeModel::Model M = getTargetMachine().getCodeModel(); 7253 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 7254 DebugLoc dl = Op.getDebugLoc(); 7255 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), 7256 /*isTarget=*/true, OpFlags); 7257 7258 if (Subtarget->isPICStyleRIPRel() && 7259 (M == CodeModel::Small || M == CodeModel::Kernel)) 7260 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7261 else 7262 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7263 7264 // With PIC, the address is actually $g + Offset. 7265 if (isGlobalRelativeToPICBase(OpFlags)) { 7266 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7267 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7268 Result); 7269 } 7270 7271 return Result; 7272} 7273 7274SDValue 7275X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl, 7276 int64_t Offset, 7277 SelectionDAG &DAG) const { 7278 // Create the TargetGlobalAddress node, folding in the constant 7279 // offset if it is legal. 7280 unsigned char OpFlags = 7281 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 7282 CodeModel::Model M = getTargetMachine().getCodeModel(); 7283 SDValue Result; 7284 if (OpFlags == X86II::MO_NO_FLAG && 7285 X86::isOffsetSuitableForCodeModel(Offset, M)) { 7286 // A direct static reference to a global. 7287 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset); 7288 Offset = 0; 7289 } else { 7290 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 7291 } 7292 7293 if (Subtarget->isPICStyleRIPRel() && 7294 (M == CodeModel::Small || M == CodeModel::Kernel)) 7295 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7296 else 7297 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7298 7299 // With PIC, the address is actually $g + Offset. 7300 if (isGlobalRelativeToPICBase(OpFlags)) { 7301 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7302 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7303 Result); 7304 } 7305 7306 // For globals that require a load from a stub to get the address, emit the 7307 // load. 7308 if (isGlobalStubReference(OpFlags)) 7309 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result, 7310 MachinePointerInfo::getGOT(), false, false, 0); 7311 7312 // If there was a non-zero offset that we didn't fold, create an explicit 7313 // addition for it. 7314 if (Offset != 0) 7315 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result, 7316 DAG.getConstant(Offset, getPointerTy())); 7317 7318 return Result; 7319} 7320 7321SDValue 7322X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { 7323 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 7324 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 7325 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG); 7326} 7327 7328static SDValue 7329GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, 7330 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg, 7331 unsigned char OperandFlags) { 7332 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7333 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7334 DebugLoc dl = GA->getDebugLoc(); 7335 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7336 GA->getValueType(0), 7337 GA->getOffset(), 7338 OperandFlags); 7339 if (InFlag) { 7340 SDValue Ops[] = { Chain, TGA, *InFlag }; 7341 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3); 7342 } else { 7343 SDValue Ops[] = { Chain, TGA }; 7344 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2); 7345 } 7346 7347 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 7348 MFI->setAdjustsStack(true); 7349 7350 SDValue Flag = Chain.getValue(1); 7351 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag); 7352} 7353 7354// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit 7355static SDValue 7356LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7357 const EVT PtrVT) { 7358 SDValue InFlag; 7359 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better 7360 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 7361 DAG.getNode(X86ISD::GlobalBaseReg, 7362 DebugLoc(), PtrVT), InFlag); 7363 InFlag = Chain.getValue(1); 7364 7365 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD); 7366} 7367 7368// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit 7369static SDValue 7370LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7371 const EVT PtrVT) { 7372 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, 7373 X86::RAX, X86II::MO_TLSGD); 7374} 7375 7376// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or 7377// "local exec" model. 7378static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7379 const EVT PtrVT, TLSModel::Model model, 7380 bool is64Bit) { 7381 DebugLoc dl = GA->getDebugLoc(); 7382 7383 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit). 7384 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(), 7385 is64Bit ? 257 : 256)); 7386 7387 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 7388 DAG.getIntPtrConstant(0), 7389 MachinePointerInfo(Ptr), false, false, 0); 7390 7391 unsigned char OperandFlags = 0; 7392 // Most TLS accesses are not RIP relative, even on x86-64. One exception is 7393 // initialexec. 7394 unsigned WrapperKind = X86ISD::Wrapper; 7395 if (model == TLSModel::LocalExec) { 7396 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF; 7397 } else if (is64Bit) { 7398 assert(model == TLSModel::InitialExec); 7399 OperandFlags = X86II::MO_GOTTPOFF; 7400 WrapperKind = X86ISD::WrapperRIP; 7401 } else { 7402 assert(model == TLSModel::InitialExec); 7403 OperandFlags = X86II::MO_INDNTPOFF; 7404 } 7405 7406 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial 7407 // exec) 7408 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7409 GA->getValueType(0), 7410 GA->getOffset(), OperandFlags); 7411 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 7412 7413 if (model == TLSModel::InitialExec) 7414 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset, 7415 MachinePointerInfo::getGOT(), false, false, 0); 7416 7417 // The address of the thread local variable is the add of the thread 7418 // pointer with the offset of the variable. 7419 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 7420} 7421 7422SDValue 7423X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 7424 7425 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 7426 const GlobalValue *GV = GA->getGlobal(); 7427 7428 if (Subtarget->isTargetELF()) { 7429 // TODO: implement the "local dynamic" model 7430 // TODO: implement the "initial exec"model for pic executables 7431 7432 // If GV is an alias then use the aliasee for determining 7433 // thread-localness. 7434 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 7435 GV = GA->resolveAliasedGlobal(false); 7436 7437 TLSModel::Model model 7438 = getTLSModel(GV, getTargetMachine().getRelocationModel()); 7439 7440 switch (model) { 7441 case TLSModel::GeneralDynamic: 7442 case TLSModel::LocalDynamic: // not implemented 7443 if (Subtarget->is64Bit()) 7444 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy()); 7445 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy()); 7446 7447 case TLSModel::InitialExec: 7448 case TLSModel::LocalExec: 7449 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, 7450 Subtarget->is64Bit()); 7451 } 7452 } else if (Subtarget->isTargetDarwin()) { 7453 // Darwin only has one model of TLS. Lower to that. 7454 unsigned char OpFlag = 0; 7455 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ? 7456 X86ISD::WrapperRIP : X86ISD::Wrapper; 7457 7458 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7459 // global base reg. 7460 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) && 7461 !Subtarget->is64Bit(); 7462 if (PIC32) 7463 OpFlag = X86II::MO_TLVP_PIC_BASE; 7464 else 7465 OpFlag = X86II::MO_TLVP; 7466 DebugLoc DL = Op.getDebugLoc(); 7467 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 7468 GA->getValueType(0), 7469 GA->getOffset(), OpFlag); 7470 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7471 7472 // With PIC32, the address is actually $g + Offset. 7473 if (PIC32) 7474 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7475 DAG.getNode(X86ISD::GlobalBaseReg, 7476 DebugLoc(), getPointerTy()), 7477 Offset); 7478 7479 // Lowering the machine isd will make sure everything is in the right 7480 // location. 7481 SDValue Chain = DAG.getEntryNode(); 7482 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7483 SDValue Args[] = { Chain, Offset }; 7484 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2); 7485 7486 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls. 7487 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7488 MFI->setAdjustsStack(true); 7489 7490 // And our return value (tls address) is in the standard call return value 7491 // location. 7492 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 7493 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy()); 7494 } 7495 7496 assert(false && 7497 "TLS not implemented for this target."); 7498 7499 llvm_unreachable("Unreachable"); 7500 return SDValue(); 7501} 7502 7503 7504/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and 7505/// take a 2 x i32 value to shift plus a shift amount. 7506SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const { 7507 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7508 EVT VT = Op.getValueType(); 7509 unsigned VTBits = VT.getSizeInBits(); 7510 DebugLoc dl = Op.getDebugLoc(); 7511 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS; 7512 SDValue ShOpLo = Op.getOperand(0); 7513 SDValue ShOpHi = Op.getOperand(1); 7514 SDValue ShAmt = Op.getOperand(2); 7515 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7516 DAG.getConstant(VTBits - 1, MVT::i8)) 7517 : DAG.getConstant(0, VT); 7518 7519 SDValue Tmp2, Tmp3; 7520 if (Op.getOpcode() == ISD::SHL_PARTS) { 7521 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt); 7522 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 7523 } else { 7524 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt); 7525 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt); 7526 } 7527 7528 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt, 7529 DAG.getConstant(VTBits, MVT::i8)); 7530 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 7531 AndNode, DAG.getConstant(0, MVT::i8)); 7532 7533 SDValue Hi, Lo; 7534 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7535 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond }; 7536 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond }; 7537 7538 if (Op.getOpcode() == ISD::SHL_PARTS) { 7539 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7540 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7541 } else { 7542 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7543 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7544 } 7545 7546 SDValue Ops[2] = { Lo, Hi }; 7547 return DAG.getMergeValues(Ops, 2, dl); 7548} 7549 7550SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, 7551 SelectionDAG &DAG) const { 7552 EVT SrcVT = Op.getOperand(0).getValueType(); 7553 7554 if (SrcVT.isVector()) 7555 return SDValue(); 7556 7557 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 && 7558 "Unknown SINT_TO_FP to lower!"); 7559 7560 // These are really Legal; return the operand so the caller accepts it as 7561 // Legal. 7562 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType())) 7563 return Op; 7564 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) && 7565 Subtarget->is64Bit()) { 7566 return Op; 7567 } 7568 7569 DebugLoc dl = Op.getDebugLoc(); 7570 unsigned Size = SrcVT.getSizeInBits()/8; 7571 MachineFunction &MF = DAG.getMachineFunction(); 7572 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false); 7573 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7574 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7575 StackSlot, 7576 MachinePointerInfo::getFixedStack(SSFI), 7577 false, false, 0); 7578 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG); 7579} 7580 7581SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain, 7582 SDValue StackSlot, 7583 SelectionDAG &DAG) const { 7584 // Build the FILD 7585 DebugLoc DL = Op.getDebugLoc(); 7586 SDVTList Tys; 7587 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType()); 7588 if (useSSE) 7589 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue); 7590 else 7591 Tys = DAG.getVTList(Op.getValueType(), MVT::Other); 7592 7593 unsigned ByteSize = SrcVT.getSizeInBits()/8; 7594 7595 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot); 7596 MachineMemOperand *MMO; 7597 if (FI) { 7598 int SSFI = FI->getIndex(); 7599 MMO = 7600 DAG.getMachineFunction() 7601 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7602 MachineMemOperand::MOLoad, ByteSize, ByteSize); 7603 } else { 7604 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand(); 7605 StackSlot = StackSlot.getOperand(1); 7606 } 7607 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; 7608 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : 7609 X86ISD::FILD, DL, 7610 Tys, Ops, array_lengthof(Ops), 7611 SrcVT, MMO); 7612 7613 if (useSSE) { 7614 Chain = Result.getValue(1); 7615 SDValue InFlag = Result.getValue(2); 7616 7617 // FIXME: Currently the FST is flagged to the FILD_FLAG. This 7618 // shouldn't be necessary except that RFP cannot be live across 7619 // multiple blocks. When stackifier is fixed, they can be uncoupled. 7620 MachineFunction &MF = DAG.getMachineFunction(); 7621 unsigned SSFISize = Op.getValueType().getSizeInBits()/8; 7622 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false); 7623 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7624 Tys = DAG.getVTList(MVT::Other); 7625 SDValue Ops[] = { 7626 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag 7627 }; 7628 MachineMemOperand *MMO = 7629 DAG.getMachineFunction() 7630 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7631 MachineMemOperand::MOStore, SSFISize, SSFISize); 7632 7633 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, 7634 Ops, array_lengthof(Ops), 7635 Op.getValueType(), MMO); 7636 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot, 7637 MachinePointerInfo::getFixedStack(SSFI), 7638 false, false, 0); 7639 } 7640 7641 return Result; 7642} 7643 7644// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion. 7645SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, 7646 SelectionDAG &DAG) const { 7647 // This algorithm is not obvious. Here it is in C code, more or less: 7648 /* 7649 double uint64_to_double( uint32_t hi, uint32_t lo ) { 7650 static const __m128i exp = { 0x4330000045300000ULL, 0 }; 7651 static const __m128d bias = { 0x1.0p84, 0x1.0p52 }; 7652 7653 // Copy ints to xmm registers. 7654 __m128i xh = _mm_cvtsi32_si128( hi ); 7655 __m128i xl = _mm_cvtsi32_si128( lo ); 7656 7657 // Combine into low half of a single xmm register. 7658 __m128i x = _mm_unpacklo_epi32( xh, xl ); 7659 __m128d d; 7660 double sd; 7661 7662 // Merge in appropriate exponents to give the integer bits the right 7663 // magnitude. 7664 x = _mm_unpacklo_epi32( x, exp ); 7665 7666 // Subtract away the biases to deal with the IEEE-754 double precision 7667 // implicit 1. 7668 d = _mm_sub_pd( (__m128d) x, bias ); 7669 7670 // All conversions up to here are exact. The correctly rounded result is 7671 // calculated using the current rounding mode using the following 7672 // horizontal add. 7673 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) ); 7674 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this 7675 // store doesn't really need to be here (except 7676 // maybe to zero the other double) 7677 return sd; 7678 } 7679 */ 7680 7681 DebugLoc dl = Op.getDebugLoc(); 7682 LLVMContext *Context = DAG.getContext(); 7683 7684 // Build some magic constants. 7685 std::vector<Constant*> CV0; 7686 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000))); 7687 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000))); 7688 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 7689 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 7690 Constant *C0 = ConstantVector::get(CV0); 7691 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16); 7692 7693 std::vector<Constant*> CV1; 7694 CV1.push_back( 7695 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL)))); 7696 CV1.push_back( 7697 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL)))); 7698 Constant *C1 = ConstantVector::get(CV1); 7699 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16); 7700 7701 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 7702 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7703 Op.getOperand(0), 7704 DAG.getIntPtrConstant(1))); 7705 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 7706 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7707 Op.getOperand(0), 7708 DAG.getIntPtrConstant(0))); 7709 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2); 7710 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0, 7711 MachinePointerInfo::getConstantPool(), 7712 false, false, 16); 7713 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0); 7714 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2); 7715 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1, 7716 MachinePointerInfo::getConstantPool(), 7717 false, false, 16); 7718 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1); 7719 7720 // Add the halves; easiest way is to swap them into another reg first. 7721 int ShufMask[2] = { 1, -1 }; 7722 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, 7723 DAG.getUNDEF(MVT::v2f64), ShufMask); 7724 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub); 7725 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add, 7726 DAG.getIntPtrConstant(0)); 7727} 7728 7729// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion. 7730SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, 7731 SelectionDAG &DAG) const { 7732 DebugLoc dl = Op.getDebugLoc(); 7733 // FP constant to bias correct the final result. 7734 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 7735 MVT::f64); 7736 7737 // Load the 32-bit value into an XMM register. 7738 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 7739 Op.getOperand(0)); 7740 7741 // Zero out the upper parts of the register. 7742 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasSSE2(), DAG); 7743 7744 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 7745 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load), 7746 DAG.getIntPtrConstant(0)); 7747 7748 // Or the load with the bias. 7749 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, 7750 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7751 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 7752 MVT::v2f64, Load)), 7753 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7754 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 7755 MVT::v2f64, Bias))); 7756 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 7757 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or), 7758 DAG.getIntPtrConstant(0)); 7759 7760 // Subtract the bias. 7761 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias); 7762 7763 // Handle final rounding. 7764 EVT DestVT = Op.getValueType(); 7765 7766 if (DestVT.bitsLT(MVT::f64)) { 7767 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 7768 DAG.getIntPtrConstant(0)); 7769 } else if (DestVT.bitsGT(MVT::f64)) { 7770 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 7771 } 7772 7773 // Handle final rounding. 7774 return Sub; 7775} 7776 7777SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, 7778 SelectionDAG &DAG) const { 7779 SDValue N0 = Op.getOperand(0); 7780 DebugLoc dl = Op.getDebugLoc(); 7781 7782 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't 7783 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform 7784 // the optimization here. 7785 if (DAG.SignBitIsZero(N0)) 7786 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0); 7787 7788 EVT SrcVT = N0.getValueType(); 7789 EVT DstVT = Op.getValueType(); 7790 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64) 7791 return LowerUINT_TO_FP_i64(Op, DAG); 7792 else if (SrcVT == MVT::i32 && X86ScalarSSEf64) 7793 return LowerUINT_TO_FP_i32(Op, DAG); 7794 7795 // Make a 64-bit buffer, and use it to build an FILD. 7796 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64); 7797 if (SrcVT == MVT::i32) { 7798 SDValue WordOff = DAG.getConstant(4, getPointerTy()); 7799 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, 7800 getPointerTy(), StackSlot, WordOff); 7801 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7802 StackSlot, MachinePointerInfo(), 7803 false, false, 0); 7804 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32), 7805 OffsetSlot, MachinePointerInfo(), 7806 false, false, 0); 7807 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG); 7808 return Fild; 7809 } 7810 7811 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"); 7812 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7813 StackSlot, MachinePointerInfo(), 7814 false, false, 0); 7815 // For i64 source, we need to add the appropriate power of 2 if the input 7816 // was negative. This is the same as the optimization in 7817 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here, 7818 // we must be careful to do the computation in x87 extended precision, not 7819 // in SSE. (The generic code can't know it's OK to do this, or how to.) 7820 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 7821 MachineMemOperand *MMO = 7822 DAG.getMachineFunction() 7823 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7824 MachineMemOperand::MOLoad, 8, 8); 7825 7826 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other); 7827 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) }; 7828 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3, 7829 MVT::i64, MMO); 7830 7831 APInt FF(32, 0x5F800000ULL); 7832 7833 // Check whether the sign bit is set. 7834 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), 7835 Op.getOperand(0), DAG.getConstant(0, MVT::i64), 7836 ISD::SETLT); 7837 7838 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits. 7839 SDValue FudgePtr = DAG.getConstantPool( 7840 ConstantInt::get(*DAG.getContext(), FF.zext(64)), 7841 getPointerTy()); 7842 7843 // Get a pointer to FF if the sign bit was set, or to 0 otherwise. 7844 SDValue Zero = DAG.getIntPtrConstant(0); 7845 SDValue Four = DAG.getIntPtrConstant(4); 7846 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, 7847 Zero, Four); 7848 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset); 7849 7850 // Load the value out, extending it from f32 to f80. 7851 // FIXME: Avoid the extend by constructing the right constant pool? 7852 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), 7853 FudgePtr, MachinePointerInfo::getConstantPool(), 7854 MVT::f32, false, false, 4); 7855 // Extend everything to 80 bits to force it to be done on x87. 7856 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge); 7857 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0)); 7858} 7859 7860std::pair<SDValue,SDValue> X86TargetLowering:: 7861FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const { 7862 DebugLoc DL = Op.getDebugLoc(); 7863 7864 EVT DstTy = Op.getValueType(); 7865 7866 if (!IsSigned) { 7867 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT"); 7868 DstTy = MVT::i64; 7869 } 7870 7871 assert(DstTy.getSimpleVT() <= MVT::i64 && 7872 DstTy.getSimpleVT() >= MVT::i16 && 7873 "Unknown FP_TO_SINT to lower!"); 7874 7875 // These are really Legal. 7876 if (DstTy == MVT::i32 && 7877 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 7878 return std::make_pair(SDValue(), SDValue()); 7879 if (Subtarget->is64Bit() && 7880 DstTy == MVT::i64 && 7881 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 7882 return std::make_pair(SDValue(), SDValue()); 7883 7884 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary 7885 // stack slot. 7886 MachineFunction &MF = DAG.getMachineFunction(); 7887 unsigned MemSize = DstTy.getSizeInBits()/8; 7888 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 7889 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7890 7891 7892 7893 unsigned Opc; 7894 switch (DstTy.getSimpleVT().SimpleTy) { 7895 default: llvm_unreachable("Invalid FP_TO_SINT to lower!"); 7896 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break; 7897 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break; 7898 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break; 7899 } 7900 7901 SDValue Chain = DAG.getEntryNode(); 7902 SDValue Value = Op.getOperand(0); 7903 EVT TheVT = Op.getOperand(0).getValueType(); 7904 if (isScalarFPTypeInSSEReg(TheVT)) { 7905 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"); 7906 Chain = DAG.getStore(Chain, DL, Value, StackSlot, 7907 MachinePointerInfo::getFixedStack(SSFI), 7908 false, false, 0); 7909 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other); 7910 SDValue Ops[] = { 7911 Chain, StackSlot, DAG.getValueType(TheVT) 7912 }; 7913 7914 MachineMemOperand *MMO = 7915 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7916 MachineMemOperand::MOLoad, MemSize, MemSize); 7917 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3, 7918 DstTy, MMO); 7919 Chain = Value.getValue(1); 7920 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 7921 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7922 } 7923 7924 MachineMemOperand *MMO = 7925 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7926 MachineMemOperand::MOStore, MemSize, MemSize); 7927 7928 // Build the FP_TO_INT*_IN_MEM 7929 SDValue Ops[] = { Chain, Value, StackSlot }; 7930 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other), 7931 Ops, 3, DstTy, MMO); 7932 7933 return std::make_pair(FIST, StackSlot); 7934} 7935 7936SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, 7937 SelectionDAG &DAG) const { 7938 if (Op.getValueType().isVector()) 7939 return SDValue(); 7940 7941 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true); 7942 SDValue FIST = Vals.first, StackSlot = Vals.second; 7943 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal. 7944 if (FIST.getNode() == 0) return Op; 7945 7946 // Load the result. 7947 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 7948 FIST, StackSlot, MachinePointerInfo(), false, false, 0); 7949} 7950 7951SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, 7952 SelectionDAG &DAG) const { 7953 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false); 7954 SDValue FIST = Vals.first, StackSlot = Vals.second; 7955 assert(FIST.getNode() && "Unexpected failure"); 7956 7957 // Load the result. 7958 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 7959 FIST, StackSlot, MachinePointerInfo(), false, false, 0); 7960} 7961 7962SDValue X86TargetLowering::LowerFABS(SDValue Op, 7963 SelectionDAG &DAG) const { 7964 LLVMContext *Context = DAG.getContext(); 7965 DebugLoc dl = Op.getDebugLoc(); 7966 EVT VT = Op.getValueType(); 7967 EVT EltVT = VT; 7968 if (VT.isVector()) 7969 EltVT = VT.getVectorElementType(); 7970 std::vector<Constant*> CV; 7971 if (EltVT == MVT::f64) { 7972 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))); 7973 CV.push_back(C); 7974 CV.push_back(C); 7975 } else { 7976 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))); 7977 CV.push_back(C); 7978 CV.push_back(C); 7979 CV.push_back(C); 7980 CV.push_back(C); 7981 } 7982 Constant *C = ConstantVector::get(CV); 7983 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7984 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 7985 MachinePointerInfo::getConstantPool(), 7986 false, false, 16); 7987 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask); 7988} 7989 7990SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const { 7991 LLVMContext *Context = DAG.getContext(); 7992 DebugLoc dl = Op.getDebugLoc(); 7993 EVT VT = Op.getValueType(); 7994 EVT EltVT = VT; 7995 if (VT.isVector()) 7996 EltVT = VT.getVectorElementType(); 7997 std::vector<Constant*> CV; 7998 if (EltVT == MVT::f64) { 7999 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))); 8000 CV.push_back(C); 8001 CV.push_back(C); 8002 } else { 8003 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))); 8004 CV.push_back(C); 8005 CV.push_back(C); 8006 CV.push_back(C); 8007 CV.push_back(C); 8008 } 8009 Constant *C = ConstantVector::get(CV); 8010 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8011 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8012 MachinePointerInfo::getConstantPool(), 8013 false, false, 16); 8014 if (VT.isVector()) { 8015 return DAG.getNode(ISD::BITCAST, dl, VT, 8016 DAG.getNode(ISD::XOR, dl, MVT::v2i64, 8017 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 8018 Op.getOperand(0)), 8019 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask))); 8020 } else { 8021 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask); 8022 } 8023} 8024 8025SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 8026 LLVMContext *Context = DAG.getContext(); 8027 SDValue Op0 = Op.getOperand(0); 8028 SDValue Op1 = Op.getOperand(1); 8029 DebugLoc dl = Op.getDebugLoc(); 8030 EVT VT = Op.getValueType(); 8031 EVT SrcVT = Op1.getValueType(); 8032 8033 // If second operand is smaller, extend it first. 8034 if (SrcVT.bitsLT(VT)) { 8035 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1); 8036 SrcVT = VT; 8037 } 8038 // And if it is bigger, shrink it first. 8039 if (SrcVT.bitsGT(VT)) { 8040 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1)); 8041 SrcVT = VT; 8042 } 8043 8044 // At this point the operands and the result should have the same 8045 // type, and that won't be f80 since that is not custom lowered. 8046 8047 // First get the sign bit of second operand. 8048 std::vector<Constant*> CV; 8049 if (SrcVT == MVT::f64) { 8050 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)))); 8051 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 8052 } else { 8053 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)))); 8054 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8055 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8056 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8057 } 8058 Constant *C = ConstantVector::get(CV); 8059 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8060 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx, 8061 MachinePointerInfo::getConstantPool(), 8062 false, false, 16); 8063 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1); 8064 8065 // Shift sign bit right or left if the two operands have different types. 8066 if (SrcVT.bitsGT(VT)) { 8067 // Op0 is MVT::f32, Op1 is MVT::f64. 8068 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit); 8069 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit, 8070 DAG.getConstant(32, MVT::i32)); 8071 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit); 8072 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit, 8073 DAG.getIntPtrConstant(0)); 8074 } 8075 8076 // Clear first operand sign bit. 8077 CV.clear(); 8078 if (VT == MVT::f64) { 8079 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))))); 8080 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 8081 } else { 8082 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))))); 8083 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8084 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8085 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8086 } 8087 C = ConstantVector::get(CV); 8088 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8089 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8090 MachinePointerInfo::getConstantPool(), 8091 false, false, 16); 8092 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2); 8093 8094 // Or the value with the sign bit. 8095 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit); 8096} 8097 8098SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const { 8099 SDValue N0 = Op.getOperand(0); 8100 DebugLoc dl = Op.getDebugLoc(); 8101 EVT VT = Op.getValueType(); 8102 8103 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1). 8104 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0, 8105 DAG.getConstant(1, VT)); 8106 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT)); 8107} 8108 8109/// Emit nodes that will be selected as "test Op0,Op0", or something 8110/// equivalent. 8111SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, 8112 SelectionDAG &DAG) const { 8113 DebugLoc dl = Op.getDebugLoc(); 8114 8115 // CF and OF aren't always set the way we want. Determine which 8116 // of these we need. 8117 bool NeedCF = false; 8118 bool NeedOF = false; 8119 switch (X86CC) { 8120 default: break; 8121 case X86::COND_A: case X86::COND_AE: 8122 case X86::COND_B: case X86::COND_BE: 8123 NeedCF = true; 8124 break; 8125 case X86::COND_G: case X86::COND_GE: 8126 case X86::COND_L: case X86::COND_LE: 8127 case X86::COND_O: case X86::COND_NO: 8128 NeedOF = true; 8129 break; 8130 } 8131 8132 // See if we can use the EFLAGS value from the operand instead of 8133 // doing a separate TEST. TEST always sets OF and CF to 0, so unless 8134 // we prove that the arithmetic won't overflow, we can't use OF or CF. 8135 if (Op.getResNo() != 0 || NeedOF || NeedCF) 8136 // Emit a CMP with 0, which is the TEST pattern. 8137 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 8138 DAG.getConstant(0, Op.getValueType())); 8139 8140 unsigned Opcode = 0; 8141 unsigned NumOperands = 0; 8142 switch (Op.getNode()->getOpcode()) { 8143 case ISD::ADD: 8144 // Due to an isel shortcoming, be conservative if this add is likely to be 8145 // selected as part of a load-modify-store instruction. When the root node 8146 // in a match is a store, isel doesn't know how to remap non-chain non-flag 8147 // uses of other nodes in the match, such as the ADD in this case. This 8148 // leads to the ADD being left around and reselected, with the result being 8149 // two adds in the output. Alas, even if none our users are stores, that 8150 // doesn't prove we're O.K. Ergo, if we have any parents that aren't 8151 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require 8152 // climbing the DAG back to the root, and it doesn't seem to be worth the 8153 // effort. 8154 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8155 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8156 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC) 8157 goto default_case; 8158 8159 if (ConstantSDNode *C = 8160 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) { 8161 // An add of one will be selected as an INC. 8162 if (C->getAPIntValue() == 1) { 8163 Opcode = X86ISD::INC; 8164 NumOperands = 1; 8165 break; 8166 } 8167 8168 // An add of negative one (subtract of one) will be selected as a DEC. 8169 if (C->getAPIntValue().isAllOnesValue()) { 8170 Opcode = X86ISD::DEC; 8171 NumOperands = 1; 8172 break; 8173 } 8174 } 8175 8176 // Otherwise use a regular EFLAGS-setting add. 8177 Opcode = X86ISD::ADD; 8178 NumOperands = 2; 8179 break; 8180 case ISD::AND: { 8181 // If the primary and result isn't used, don't bother using X86ISD::AND, 8182 // because a TEST instruction will be better. 8183 bool NonFlagUse = false; 8184 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8185 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 8186 SDNode *User = *UI; 8187 unsigned UOpNo = UI.getOperandNo(); 8188 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) { 8189 // Look pass truncate. 8190 UOpNo = User->use_begin().getOperandNo(); 8191 User = *User->use_begin(); 8192 } 8193 8194 if (User->getOpcode() != ISD::BRCOND && 8195 User->getOpcode() != ISD::SETCC && 8196 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) { 8197 NonFlagUse = true; 8198 break; 8199 } 8200 } 8201 8202 if (!NonFlagUse) 8203 break; 8204 } 8205 // FALL THROUGH 8206 case ISD::SUB: 8207 case ISD::OR: 8208 case ISD::XOR: 8209 // Due to the ISEL shortcoming noted above, be conservative if this op is 8210 // likely to be selected as part of a load-modify-store instruction. 8211 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8212 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8213 if (UI->getOpcode() == ISD::STORE) 8214 goto default_case; 8215 8216 // Otherwise use a regular EFLAGS-setting instruction. 8217 switch (Op.getNode()->getOpcode()) { 8218 default: llvm_unreachable("unexpected operator!"); 8219 case ISD::SUB: Opcode = X86ISD::SUB; break; 8220 case ISD::OR: Opcode = X86ISD::OR; break; 8221 case ISD::XOR: Opcode = X86ISD::XOR; break; 8222 case ISD::AND: Opcode = X86ISD::AND; break; 8223 } 8224 8225 NumOperands = 2; 8226 break; 8227 case X86ISD::ADD: 8228 case X86ISD::SUB: 8229 case X86ISD::INC: 8230 case X86ISD::DEC: 8231 case X86ISD::OR: 8232 case X86ISD::XOR: 8233 case X86ISD::AND: 8234 return SDValue(Op.getNode(), 1); 8235 default: 8236 default_case: 8237 break; 8238 } 8239 8240 if (Opcode == 0) 8241 // Emit a CMP with 0, which is the TEST pattern. 8242 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 8243 DAG.getConstant(0, Op.getValueType())); 8244 8245 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 8246 SmallVector<SDValue, 4> Ops; 8247 for (unsigned i = 0; i != NumOperands; ++i) 8248 Ops.push_back(Op.getOperand(i)); 8249 8250 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands); 8251 DAG.ReplaceAllUsesWith(Op, New); 8252 return SDValue(New.getNode(), 1); 8253} 8254 8255/// Emit nodes that will be selected as "cmp Op0,Op1", or something 8256/// equivalent. 8257SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC, 8258 SelectionDAG &DAG) const { 8259 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) 8260 if (C->getAPIntValue() == 0) 8261 return EmitTest(Op0, X86CC, DAG); 8262 8263 DebugLoc dl = Op0.getDebugLoc(); 8264 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1); 8265} 8266 8267/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node 8268/// if it's possible. 8269SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC, 8270 DebugLoc dl, SelectionDAG &DAG) const { 8271 SDValue Op0 = And.getOperand(0); 8272 SDValue Op1 = And.getOperand(1); 8273 if (Op0.getOpcode() == ISD::TRUNCATE) 8274 Op0 = Op0.getOperand(0); 8275 if (Op1.getOpcode() == ISD::TRUNCATE) 8276 Op1 = Op1.getOperand(0); 8277 8278 SDValue LHS, RHS; 8279 if (Op1.getOpcode() == ISD::SHL) 8280 std::swap(Op0, Op1); 8281 if (Op0.getOpcode() == ISD::SHL) { 8282 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0))) 8283 if (And00C->getZExtValue() == 1) { 8284 // If we looked past a truncate, check that it's only truncating away 8285 // known zeros. 8286 unsigned BitWidth = Op0.getValueSizeInBits(); 8287 unsigned AndBitWidth = And.getValueSizeInBits(); 8288 if (BitWidth > AndBitWidth) { 8289 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones; 8290 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones); 8291 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth) 8292 return SDValue(); 8293 } 8294 LHS = Op1; 8295 RHS = Op0.getOperand(1); 8296 } 8297 } else if (Op1.getOpcode() == ISD::Constant) { 8298 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1); 8299 SDValue AndLHS = Op0; 8300 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) { 8301 LHS = AndLHS.getOperand(0); 8302 RHS = AndLHS.getOperand(1); 8303 } 8304 } 8305 8306 if (LHS.getNode()) { 8307 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT 8308 // instruction. Since the shift amount is in-range-or-undefined, we know 8309 // that doing a bittest on the i32 value is ok. We extend to i32 because 8310 // the encoding for the i16 version is larger than the i32 version. 8311 // Also promote i16 to i32 for performance / code size reason. 8312 if (LHS.getValueType() == MVT::i8 || 8313 LHS.getValueType() == MVT::i16) 8314 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 8315 8316 // If the operand types disagree, extend the shift amount to match. Since 8317 // BT ignores high bits (like shifts) we can use anyextend. 8318 if (LHS.getValueType() != RHS.getValueType()) 8319 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS); 8320 8321 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS); 8322 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B; 8323 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8324 DAG.getConstant(Cond, MVT::i8), BT); 8325 } 8326 8327 return SDValue(); 8328} 8329 8330SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 8331 8332 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG); 8333 8334 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer"); 8335 SDValue Op0 = Op.getOperand(0); 8336 SDValue Op1 = Op.getOperand(1); 8337 DebugLoc dl = Op.getDebugLoc(); 8338 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8339 8340 // Optimize to BT if possible. 8341 // Lower (X & (1 << N)) == 0 to BT(X, N). 8342 // Lower ((X >>u N) & 1) != 0 to BT(X, N). 8343 // Lower ((X >>s N) & 1) != 0 to BT(X, N). 8344 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && 8345 Op1.getOpcode() == ISD::Constant && 8346 cast<ConstantSDNode>(Op1)->isNullValue() && 8347 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 8348 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG); 8349 if (NewSetCC.getNode()) 8350 return NewSetCC; 8351 } 8352 8353 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of 8354 // these. 8355 if (Op1.getOpcode() == ISD::Constant && 8356 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 || 8357 cast<ConstantSDNode>(Op1)->isNullValue()) && 8358 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 8359 8360 // If the input is a setcc, then reuse the input setcc or use a new one with 8361 // the inverted condition. 8362 if (Op0.getOpcode() == X86ISD::SETCC) { 8363 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0); 8364 bool Invert = (CC == ISD::SETNE) ^ 8365 cast<ConstantSDNode>(Op1)->isNullValue(); 8366 if (!Invert) return Op0; 8367 8368 CCode = X86::GetOppositeBranchCondition(CCode); 8369 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8370 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1)); 8371 } 8372 } 8373 8374 bool isFP = Op1.getValueType().isFloatingPoint(); 8375 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 8376 if (X86CC == X86::COND_INVALID) 8377 return SDValue(); 8378 8379 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG); 8380 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8381 DAG.getConstant(X86CC, MVT::i8), EFLAGS); 8382} 8383 8384// Lower256IntVETCC - Break a VSETCC 256-bit integer VSETCC into two new 128 8385// ones, and then concatenate the result back. 8386static SDValue Lower256IntVETCC(SDValue Op, SelectionDAG &DAG) { 8387 EVT VT = Op.getValueType(); 8388 8389 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC && 8390 "Unsupported value type for operation"); 8391 8392 int NumElems = VT.getVectorNumElements(); 8393 DebugLoc dl = Op.getDebugLoc(); 8394 SDValue CC = Op.getOperand(2); 8395 SDValue Idx0 = DAG.getConstant(0, MVT::i32); 8396 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32); 8397 8398 // Extract the LHS vectors 8399 SDValue LHS = Op.getOperand(0); 8400 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl); 8401 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl); 8402 8403 // Extract the RHS vectors 8404 SDValue RHS = Op.getOperand(1); 8405 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl); 8406 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl); 8407 8408 // Issue the operation on the smaller types and concatenate the result back 8409 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 8410 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 8411 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 8412 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC), 8413 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC)); 8414} 8415 8416 8417SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const { 8418 SDValue Cond; 8419 SDValue Op0 = Op.getOperand(0); 8420 SDValue Op1 = Op.getOperand(1); 8421 SDValue CC = Op.getOperand(2); 8422 EVT VT = Op.getValueType(); 8423 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 8424 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint(); 8425 DebugLoc dl = Op.getDebugLoc(); 8426 8427 if (isFP) { 8428 unsigned SSECC = 8; 8429 EVT EltVT = Op0.getValueType().getVectorElementType(); 8430 assert(EltVT == MVT::f32 || EltVT == MVT::f64); 8431 8432 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD; 8433 bool Swap = false; 8434 8435 switch (SetCCOpcode) { 8436 default: break; 8437 case ISD::SETOEQ: 8438 case ISD::SETEQ: SSECC = 0; break; 8439 case ISD::SETOGT: 8440 case ISD::SETGT: Swap = true; // Fallthrough 8441 case ISD::SETLT: 8442 case ISD::SETOLT: SSECC = 1; break; 8443 case ISD::SETOGE: 8444 case ISD::SETGE: Swap = true; // Fallthrough 8445 case ISD::SETLE: 8446 case ISD::SETOLE: SSECC = 2; break; 8447 case ISD::SETUO: SSECC = 3; break; 8448 case ISD::SETUNE: 8449 case ISD::SETNE: SSECC = 4; break; 8450 case ISD::SETULE: Swap = true; 8451 case ISD::SETUGE: SSECC = 5; break; 8452 case ISD::SETULT: Swap = true; 8453 case ISD::SETUGT: SSECC = 6; break; 8454 case ISD::SETO: SSECC = 7; break; 8455 } 8456 if (Swap) 8457 std::swap(Op0, Op1); 8458 8459 // In the two special cases we can't handle, emit two comparisons. 8460 if (SSECC == 8) { 8461 if (SetCCOpcode == ISD::SETUEQ) { 8462 SDValue UNORD, EQ; 8463 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8)); 8464 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8)); 8465 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ); 8466 } 8467 else if (SetCCOpcode == ISD::SETONE) { 8468 SDValue ORD, NEQ; 8469 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8)); 8470 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8)); 8471 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ); 8472 } 8473 llvm_unreachable("Illegal FP comparison"); 8474 } 8475 // Handle all other FP comparisons here. 8476 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8)); 8477 } 8478 8479 // Break 256-bit integer vector compare into smaller ones. 8480 if (!isFP && VT.getSizeInBits() == 256) 8481 return Lower256IntVETCC(Op, DAG); 8482 8483 // We are handling one of the integer comparisons here. Since SSE only has 8484 // GT and EQ comparisons for integer, swapping operands and multiple 8485 // operations may be required for some comparisons. 8486 unsigned Opc = 0, EQOpc = 0, GTOpc = 0; 8487 bool Swap = false, Invert = false, FlipSigns = false; 8488 8489 switch (VT.getSimpleVT().SimpleTy) { 8490 default: break; 8491 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break; 8492 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break; 8493 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break; 8494 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break; 8495 } 8496 8497 switch (SetCCOpcode) { 8498 default: break; 8499 case ISD::SETNE: Invert = true; 8500 case ISD::SETEQ: Opc = EQOpc; break; 8501 case ISD::SETLT: Swap = true; 8502 case ISD::SETGT: Opc = GTOpc; break; 8503 case ISD::SETGE: Swap = true; 8504 case ISD::SETLE: Opc = GTOpc; Invert = true; break; 8505 case ISD::SETULT: Swap = true; 8506 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break; 8507 case ISD::SETUGE: Swap = true; 8508 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break; 8509 } 8510 if (Swap) 8511 std::swap(Op0, Op1); 8512 8513 // Since SSE has no unsigned integer comparisons, we need to flip the sign 8514 // bits of the inputs before performing those operations. 8515 if (FlipSigns) { 8516 EVT EltVT = VT.getVectorElementType(); 8517 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), 8518 EltVT); 8519 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit); 8520 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0], 8521 SignBits.size()); 8522 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec); 8523 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec); 8524 } 8525 8526 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 8527 8528 // If the logical-not of the result is required, perform that now. 8529 if (Invert) 8530 Result = DAG.getNOT(dl, Result, VT); 8531 8532 return Result; 8533} 8534 8535// isX86LogicalCmp - Return true if opcode is a X86 logical comparison. 8536static bool isX86LogicalCmp(SDValue Op) { 8537 unsigned Opc = Op.getNode()->getOpcode(); 8538 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) 8539 return true; 8540 if (Op.getResNo() == 1 && 8541 (Opc == X86ISD::ADD || 8542 Opc == X86ISD::SUB || 8543 Opc == X86ISD::ADC || 8544 Opc == X86ISD::SBB || 8545 Opc == X86ISD::SMUL || 8546 Opc == X86ISD::UMUL || 8547 Opc == X86ISD::INC || 8548 Opc == X86ISD::DEC || 8549 Opc == X86ISD::OR || 8550 Opc == X86ISD::XOR || 8551 Opc == X86ISD::AND)) 8552 return true; 8553 8554 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL) 8555 return true; 8556 8557 return false; 8558} 8559 8560static bool isZero(SDValue V) { 8561 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 8562 return C && C->isNullValue(); 8563} 8564 8565static bool isAllOnes(SDValue V) { 8566 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 8567 return C && C->isAllOnesValue(); 8568} 8569 8570SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8571 bool addTest = true; 8572 SDValue Cond = Op.getOperand(0); 8573 SDValue Op1 = Op.getOperand(1); 8574 SDValue Op2 = Op.getOperand(2); 8575 DebugLoc DL = Op.getDebugLoc(); 8576 SDValue CC; 8577 8578 if (Cond.getOpcode() == ISD::SETCC) { 8579 SDValue NewCond = LowerSETCC(Cond, DAG); 8580 if (NewCond.getNode()) 8581 Cond = NewCond; 8582 } 8583 8584 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y 8585 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y 8586 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y 8587 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y 8588 if (Cond.getOpcode() == X86ISD::SETCC && 8589 Cond.getOperand(1).getOpcode() == X86ISD::CMP && 8590 isZero(Cond.getOperand(1).getOperand(1))) { 8591 SDValue Cmp = Cond.getOperand(1); 8592 8593 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue(); 8594 8595 if ((isAllOnes(Op1) || isAllOnes(Op2)) && 8596 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) { 8597 SDValue Y = isAllOnes(Op2) ? Op1 : Op2; 8598 8599 SDValue CmpOp0 = Cmp.getOperand(0); 8600 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, 8601 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType())); 8602 8603 SDValue Res = // Res = 0 or -1. 8604 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 8605 DAG.getConstant(X86::COND_B, MVT::i8), Cmp); 8606 8607 if (isAllOnes(Op1) != (CondCode == X86::COND_E)) 8608 Res = DAG.getNOT(DL, Res, Res.getValueType()); 8609 8610 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2); 8611 if (N2C == 0 || !N2C->isNullValue()) 8612 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y); 8613 return Res; 8614 } 8615 } 8616 8617 // Look past (and (setcc_carry (cmp ...)), 1). 8618 if (Cond.getOpcode() == ISD::AND && 8619 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 8620 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 8621 if (C && C->getAPIntValue() == 1) 8622 Cond = Cond.getOperand(0); 8623 } 8624 8625 // If condition flag is set by a X86ISD::CMP, then use it as the condition 8626 // setting operand in place of the X86ISD::SETCC. 8627 if (Cond.getOpcode() == X86ISD::SETCC || 8628 Cond.getOpcode() == X86ISD::SETCC_CARRY) { 8629 CC = Cond.getOperand(0); 8630 8631 SDValue Cmp = Cond.getOperand(1); 8632 unsigned Opc = Cmp.getOpcode(); 8633 EVT VT = Op.getValueType(); 8634 8635 bool IllegalFPCMov = false; 8636 if (VT.isFloatingPoint() && !VT.isVector() && 8637 !isScalarFPTypeInSSEReg(VT)) // FPStack? 8638 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue()); 8639 8640 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || 8641 Opc == X86ISD::BT) { // FIXME 8642 Cond = Cmp; 8643 addTest = false; 8644 } 8645 } 8646 8647 if (addTest) { 8648 // Look pass the truncate. 8649 if (Cond.getOpcode() == ISD::TRUNCATE) 8650 Cond = Cond.getOperand(0); 8651 8652 // We know the result of AND is compared against zero. Try to match 8653 // it to BT. 8654 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 8655 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG); 8656 if (NewSetCC.getNode()) { 8657 CC = NewSetCC.getOperand(0); 8658 Cond = NewSetCC.getOperand(1); 8659 addTest = false; 8660 } 8661 } 8662 } 8663 8664 if (addTest) { 8665 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 8666 Cond = EmitTest(Cond, X86::COND_NE, DAG); 8667 } 8668 8669 // a < b ? -1 : 0 -> RES = ~setcc_carry 8670 // a < b ? 0 : -1 -> RES = setcc_carry 8671 // a >= b ? -1 : 0 -> RES = setcc_carry 8672 // a >= b ? 0 : -1 -> RES = ~setcc_carry 8673 if (Cond.getOpcode() == X86ISD::CMP) { 8674 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue(); 8675 8676 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) && 8677 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) { 8678 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 8679 DAG.getConstant(X86::COND_B, MVT::i8), Cond); 8680 if (isAllOnes(Op1) != (CondCode == X86::COND_B)) 8681 return DAG.getNOT(DL, Res, Res.getValueType()); 8682 return Res; 8683 } 8684 } 8685 8686 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if 8687 // condition is true. 8688 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 8689 SDValue Ops[] = { Op2, Op1, CC, Cond }; 8690 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops)); 8691} 8692 8693SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const { 8694 SDValue Cond = Op.getOperand(0); 8695 SDValue Op1 = Op.getOperand(1); 8696 SDValue Op2 = Op.getOperand(2); 8697 DebugLoc DL = Op.getDebugLoc(); 8698 8699 SDValue Ops[] = {Op1, Op2, Cond}; 8700 8701 assert(Op1.getValueType().isVector() && "Op1 must be a vector"); 8702 assert(Op2.getValueType().isVector() && "Op2 must be a vector"); 8703 assert(Cond.getValueType().isVector() && "Cond must be a vector"); 8704 assert(Op1.getValueType() == Op2.getValueType() && "Type mismatch"); 8705 8706 EVT VT = Op1.getValueType(); 8707 switch (VT.getSimpleVT().SimpleTy) { 8708 default: break; 8709 case MVT::v2i64: 8710 case MVT::v2f64: 8711 return DAG.getNode(X86ISD::BLENDVPD, DL, VT, Ops, array_lengthof(Ops)); 8712 case MVT::v4i32: 8713 case MVT::v4f32: 8714 return DAG.getNode(X86ISD::BLENDVPS, DL, VT , Ops, array_lengthof(Ops)); 8715 case MVT::v16i8: 8716 return DAG.getNode(X86ISD::PBLENDVB, DL, VT , Ops, array_lengthof(Ops)); 8717 } 8718 8719 return SDValue(); 8720} 8721 8722 8723// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or 8724// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart 8725// from the AND / OR. 8726static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) { 8727 Opc = Op.getOpcode(); 8728 if (Opc != ISD::OR && Opc != ISD::AND) 8729 return false; 8730 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC && 8731 Op.getOperand(0).hasOneUse() && 8732 Op.getOperand(1).getOpcode() == X86ISD::SETCC && 8733 Op.getOperand(1).hasOneUse()); 8734} 8735 8736// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and 8737// 1 and that the SETCC node has a single use. 8738static bool isXor1OfSetCC(SDValue Op) { 8739 if (Op.getOpcode() != ISD::XOR) 8740 return false; 8741 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8742 if (N1C && N1C->getAPIntValue() == 1) { 8743 return Op.getOperand(0).getOpcode() == X86ISD::SETCC && 8744 Op.getOperand(0).hasOneUse(); 8745 } 8746 return false; 8747} 8748 8749SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 8750 bool addTest = true; 8751 SDValue Chain = Op.getOperand(0); 8752 SDValue Cond = Op.getOperand(1); 8753 SDValue Dest = Op.getOperand(2); 8754 DebugLoc dl = Op.getDebugLoc(); 8755 SDValue CC; 8756 8757 if (Cond.getOpcode() == ISD::SETCC) { 8758 SDValue NewCond = LowerSETCC(Cond, DAG); 8759 if (NewCond.getNode()) 8760 Cond = NewCond; 8761 } 8762#if 0 8763 // FIXME: LowerXALUO doesn't handle these!! 8764 else if (Cond.getOpcode() == X86ISD::ADD || 8765 Cond.getOpcode() == X86ISD::SUB || 8766 Cond.getOpcode() == X86ISD::SMUL || 8767 Cond.getOpcode() == X86ISD::UMUL) 8768 Cond = LowerXALUO(Cond, DAG); 8769#endif 8770 8771 // Look pass (and (setcc_carry (cmp ...)), 1). 8772 if (Cond.getOpcode() == ISD::AND && 8773 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 8774 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 8775 if (C && C->getAPIntValue() == 1) 8776 Cond = Cond.getOperand(0); 8777 } 8778 8779 // If condition flag is set by a X86ISD::CMP, then use it as the condition 8780 // setting operand in place of the X86ISD::SETCC. 8781 if (Cond.getOpcode() == X86ISD::SETCC || 8782 Cond.getOpcode() == X86ISD::SETCC_CARRY) { 8783 CC = Cond.getOperand(0); 8784 8785 SDValue Cmp = Cond.getOperand(1); 8786 unsigned Opc = Cmp.getOpcode(); 8787 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp?? 8788 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) { 8789 Cond = Cmp; 8790 addTest = false; 8791 } else { 8792 switch (cast<ConstantSDNode>(CC)->getZExtValue()) { 8793 default: break; 8794 case X86::COND_O: 8795 case X86::COND_B: 8796 // These can only come from an arithmetic instruction with overflow, 8797 // e.g. SADDO, UADDO. 8798 Cond = Cond.getNode()->getOperand(1); 8799 addTest = false; 8800 break; 8801 } 8802 } 8803 } else { 8804 unsigned CondOpc; 8805 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) { 8806 SDValue Cmp = Cond.getOperand(0).getOperand(1); 8807 if (CondOpc == ISD::OR) { 8808 // Also, recognize the pattern generated by an FCMP_UNE. We can emit 8809 // two branches instead of an explicit OR instruction with a 8810 // separate test. 8811 if (Cmp == Cond.getOperand(1).getOperand(1) && 8812 isX86LogicalCmp(Cmp)) { 8813 CC = Cond.getOperand(0).getOperand(0); 8814 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 8815 Chain, Dest, CC, Cmp); 8816 CC = Cond.getOperand(1).getOperand(0); 8817 Cond = Cmp; 8818 addTest = false; 8819 } 8820 } else { // ISD::AND 8821 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit 8822 // two branches instead of an explicit AND instruction with a 8823 // separate test. However, we only do this if this block doesn't 8824 // have a fall-through edge, because this requires an explicit 8825 // jmp when the condition is false. 8826 if (Cmp == Cond.getOperand(1).getOperand(1) && 8827 isX86LogicalCmp(Cmp) && 8828 Op.getNode()->hasOneUse()) { 8829 X86::CondCode CCode = 8830 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 8831 CCode = X86::GetOppositeBranchCondition(CCode); 8832 CC = DAG.getConstant(CCode, MVT::i8); 8833 SDNode *User = *Op.getNode()->use_begin(); 8834 // Look for an unconditional branch following this conditional branch. 8835 // We need this because we need to reverse the successors in order 8836 // to implement FCMP_OEQ. 8837 if (User->getOpcode() == ISD::BR) { 8838 SDValue FalseBB = User->getOperand(1); 8839 SDNode *NewBR = 8840 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 8841 assert(NewBR == User); 8842 (void)NewBR; 8843 Dest = FalseBB; 8844 8845 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 8846 Chain, Dest, CC, Cmp); 8847 X86::CondCode CCode = 8848 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0); 8849 CCode = X86::GetOppositeBranchCondition(CCode); 8850 CC = DAG.getConstant(CCode, MVT::i8); 8851 Cond = Cmp; 8852 addTest = false; 8853 } 8854 } 8855 } 8856 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) { 8857 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition. 8858 // It should be transformed during dag combiner except when the condition 8859 // is set by a arithmetics with overflow node. 8860 X86::CondCode CCode = 8861 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 8862 CCode = X86::GetOppositeBranchCondition(CCode); 8863 CC = DAG.getConstant(CCode, MVT::i8); 8864 Cond = Cond.getOperand(0).getOperand(1); 8865 addTest = false; 8866 } 8867 } 8868 8869 if (addTest) { 8870 // Look pass the truncate. 8871 if (Cond.getOpcode() == ISD::TRUNCATE) 8872 Cond = Cond.getOperand(0); 8873 8874 // We know the result of AND is compared against zero. Try to match 8875 // it to BT. 8876 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 8877 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG); 8878 if (NewSetCC.getNode()) { 8879 CC = NewSetCC.getOperand(0); 8880 Cond = NewSetCC.getOperand(1); 8881 addTest = false; 8882 } 8883 } 8884 } 8885 8886 if (addTest) { 8887 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 8888 Cond = EmitTest(Cond, X86::COND_NE, DAG); 8889 } 8890 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 8891 Chain, Dest, CC, Cond); 8892} 8893 8894 8895// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets. 8896// Calls to _alloca is needed to probe the stack when allocating more than 4k 8897// bytes in one go. Touching the stack at 4K increments is necessary to ensure 8898// that the guard pages used by the OS virtual memory manager are allocated in 8899// correct sequence. 8900SDValue 8901X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 8902 SelectionDAG &DAG) const { 8903 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() || 8904 EnableSegmentedStacks) && 8905 "This should be used only on Windows targets or when segmented stacks " 8906 "are being used"); 8907 assert(!Subtarget->isTargetEnvMacho() && "Not implemented"); 8908 DebugLoc dl = Op.getDebugLoc(); 8909 8910 // Get the inputs. 8911 SDValue Chain = Op.getOperand(0); 8912 SDValue Size = Op.getOperand(1); 8913 // FIXME: Ensure alignment here 8914 8915 bool Is64Bit = Subtarget->is64Bit(); 8916 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32; 8917 8918 if (EnableSegmentedStacks) { 8919 MachineFunction &MF = DAG.getMachineFunction(); 8920 MachineRegisterInfo &MRI = MF.getRegInfo(); 8921 8922 if (Is64Bit) { 8923 // The 64 bit implementation of segmented stacks needs to clobber both r10 8924 // r11. This makes it impossible to use it along with nested parameters. 8925 const Function *F = MF.getFunction(); 8926 8927 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 8928 I != E; I++) 8929 if (I->hasNestAttr()) 8930 report_fatal_error("Cannot use segmented stacks with functions that " 8931 "have nested arguments."); 8932 } 8933 8934 const TargetRegisterClass *AddrRegClass = 8935 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32); 8936 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass); 8937 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size); 8938 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain, 8939 DAG.getRegister(Vreg, SPTy)); 8940 SDValue Ops1[2] = { Value, Chain }; 8941 return DAG.getMergeValues(Ops1, 2, dl); 8942 } else { 8943 SDValue Flag; 8944 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX); 8945 8946 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag); 8947 Flag = Chain.getValue(1); 8948 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8949 8950 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag); 8951 Flag = Chain.getValue(1); 8952 8953 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1); 8954 8955 SDValue Ops1[2] = { Chain.getValue(0), Chain }; 8956 return DAG.getMergeValues(Ops1, 2, dl); 8957 } 8958} 8959 8960SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 8961 MachineFunction &MF = DAG.getMachineFunction(); 8962 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 8963 8964 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 8965 DebugLoc DL = Op.getDebugLoc(); 8966 8967 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) { 8968 // vastart just stores the address of the VarArgsFrameIndex slot into the 8969 // memory location argument. 8970 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 8971 getPointerTy()); 8972 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 8973 MachinePointerInfo(SV), false, false, 0); 8974 } 8975 8976 // __va_list_tag: 8977 // gp_offset (0 - 6 * 8) 8978 // fp_offset (48 - 48 + 8 * 16) 8979 // overflow_arg_area (point to parameters coming in memory). 8980 // reg_save_area 8981 SmallVector<SDValue, 8> MemOps; 8982 SDValue FIN = Op.getOperand(1); 8983 // Store gp_offset 8984 SDValue Store = DAG.getStore(Op.getOperand(0), DL, 8985 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), 8986 MVT::i32), 8987 FIN, MachinePointerInfo(SV), false, false, 0); 8988 MemOps.push_back(Store); 8989 8990 // Store fp_offset 8991 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 8992 FIN, DAG.getIntPtrConstant(4)); 8993 Store = DAG.getStore(Op.getOperand(0), DL, 8994 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), 8995 MVT::i32), 8996 FIN, MachinePointerInfo(SV, 4), false, false, 0); 8997 MemOps.push_back(Store); 8998 8999 // Store ptr to overflow_arg_area 9000 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9001 FIN, DAG.getIntPtrConstant(4)); 9002 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 9003 getPointerTy()); 9004 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, 9005 MachinePointerInfo(SV, 8), 9006 false, false, 0); 9007 MemOps.push_back(Store); 9008 9009 // Store ptr to reg_save_area. 9010 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9011 FIN, DAG.getIntPtrConstant(8)); 9012 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 9013 getPointerTy()); 9014 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, 9015 MachinePointerInfo(SV, 16), false, false, 0); 9016 MemOps.push_back(Store); 9017 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 9018 &MemOps[0], MemOps.size()); 9019} 9020 9021SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 9022 assert(Subtarget->is64Bit() && 9023 "LowerVAARG only handles 64-bit va_arg!"); 9024 assert((Subtarget->isTargetLinux() || 9025 Subtarget->isTargetDarwin()) && 9026 "Unhandled target in LowerVAARG"); 9027 assert(Op.getNode()->getNumOperands() == 4); 9028 SDValue Chain = Op.getOperand(0); 9029 SDValue SrcPtr = Op.getOperand(1); 9030 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 9031 unsigned Align = Op.getConstantOperandVal(3); 9032 DebugLoc dl = Op.getDebugLoc(); 9033 9034 EVT ArgVT = Op.getNode()->getValueType(0); 9035 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 9036 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy); 9037 uint8_t ArgMode; 9038 9039 // Decide which area this value should be read from. 9040 // TODO: Implement the AMD64 ABI in its entirety. This simple 9041 // selection mechanism works only for the basic types. 9042 if (ArgVT == MVT::f80) { 9043 llvm_unreachable("va_arg for f80 not yet implemented"); 9044 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) { 9045 ArgMode = 2; // Argument passed in XMM register. Use fp_offset. 9046 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) { 9047 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset. 9048 } else { 9049 llvm_unreachable("Unhandled argument type in LowerVAARG"); 9050 } 9051 9052 if (ArgMode == 2) { 9053 // Sanity Check: Make sure using fp_offset makes sense. 9054 assert(!UseSoftFloat && 9055 !(DAG.getMachineFunction() 9056 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) && 9057 Subtarget->hasXMM()); 9058 } 9059 9060 // Insert VAARG_64 node into the DAG 9061 // VAARG_64 returns two values: Variable Argument Address, Chain 9062 SmallVector<SDValue, 11> InstOps; 9063 InstOps.push_back(Chain); 9064 InstOps.push_back(SrcPtr); 9065 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32)); 9066 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8)); 9067 InstOps.push_back(DAG.getConstant(Align, MVT::i32)); 9068 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other); 9069 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl, 9070 VTs, &InstOps[0], InstOps.size(), 9071 MVT::i64, 9072 MachinePointerInfo(SV), 9073 /*Align=*/0, 9074 /*Volatile=*/false, 9075 /*ReadMem=*/true, 9076 /*WriteMem=*/true); 9077 Chain = VAARG.getValue(1); 9078 9079 // Load the next argument and return it 9080 return DAG.getLoad(ArgVT, dl, 9081 Chain, 9082 VAARG, 9083 MachinePointerInfo(), 9084 false, false, 0); 9085} 9086 9087SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 9088 // X86-64 va_list is a struct { i32, i32, i8*, i8* }. 9089 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!"); 9090 SDValue Chain = Op.getOperand(0); 9091 SDValue DstPtr = Op.getOperand(1); 9092 SDValue SrcPtr = Op.getOperand(2); 9093 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 9094 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 9095 DebugLoc DL = Op.getDebugLoc(); 9096 9097 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, 9098 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false, 9099 false, 9100 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 9101} 9102 9103SDValue 9104X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const { 9105 DebugLoc dl = Op.getDebugLoc(); 9106 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9107 switch (IntNo) { 9108 default: return SDValue(); // Don't custom lower most intrinsics. 9109 // Comparison intrinsics. 9110 case Intrinsic::x86_sse_comieq_ss: 9111 case Intrinsic::x86_sse_comilt_ss: 9112 case Intrinsic::x86_sse_comile_ss: 9113 case Intrinsic::x86_sse_comigt_ss: 9114 case Intrinsic::x86_sse_comige_ss: 9115 case Intrinsic::x86_sse_comineq_ss: 9116 case Intrinsic::x86_sse_ucomieq_ss: 9117 case Intrinsic::x86_sse_ucomilt_ss: 9118 case Intrinsic::x86_sse_ucomile_ss: 9119 case Intrinsic::x86_sse_ucomigt_ss: 9120 case Intrinsic::x86_sse_ucomige_ss: 9121 case Intrinsic::x86_sse_ucomineq_ss: 9122 case Intrinsic::x86_sse2_comieq_sd: 9123 case Intrinsic::x86_sse2_comilt_sd: 9124 case Intrinsic::x86_sse2_comile_sd: 9125 case Intrinsic::x86_sse2_comigt_sd: 9126 case Intrinsic::x86_sse2_comige_sd: 9127 case Intrinsic::x86_sse2_comineq_sd: 9128 case Intrinsic::x86_sse2_ucomieq_sd: 9129 case Intrinsic::x86_sse2_ucomilt_sd: 9130 case Intrinsic::x86_sse2_ucomile_sd: 9131 case Intrinsic::x86_sse2_ucomigt_sd: 9132 case Intrinsic::x86_sse2_ucomige_sd: 9133 case Intrinsic::x86_sse2_ucomineq_sd: { 9134 unsigned Opc = 0; 9135 ISD::CondCode CC = ISD::SETCC_INVALID; 9136 switch (IntNo) { 9137 default: break; 9138 case Intrinsic::x86_sse_comieq_ss: 9139 case Intrinsic::x86_sse2_comieq_sd: 9140 Opc = X86ISD::COMI; 9141 CC = ISD::SETEQ; 9142 break; 9143 case Intrinsic::x86_sse_comilt_ss: 9144 case Intrinsic::x86_sse2_comilt_sd: 9145 Opc = X86ISD::COMI; 9146 CC = ISD::SETLT; 9147 break; 9148 case Intrinsic::x86_sse_comile_ss: 9149 case Intrinsic::x86_sse2_comile_sd: 9150 Opc = X86ISD::COMI; 9151 CC = ISD::SETLE; 9152 break; 9153 case Intrinsic::x86_sse_comigt_ss: 9154 case Intrinsic::x86_sse2_comigt_sd: 9155 Opc = X86ISD::COMI; 9156 CC = ISD::SETGT; 9157 break; 9158 case Intrinsic::x86_sse_comige_ss: 9159 case Intrinsic::x86_sse2_comige_sd: 9160 Opc = X86ISD::COMI; 9161 CC = ISD::SETGE; 9162 break; 9163 case Intrinsic::x86_sse_comineq_ss: 9164 case Intrinsic::x86_sse2_comineq_sd: 9165 Opc = X86ISD::COMI; 9166 CC = ISD::SETNE; 9167 break; 9168 case Intrinsic::x86_sse_ucomieq_ss: 9169 case Intrinsic::x86_sse2_ucomieq_sd: 9170 Opc = X86ISD::UCOMI; 9171 CC = ISD::SETEQ; 9172 break; 9173 case Intrinsic::x86_sse_ucomilt_ss: 9174 case Intrinsic::x86_sse2_ucomilt_sd: 9175 Opc = X86ISD::UCOMI; 9176 CC = ISD::SETLT; 9177 break; 9178 case Intrinsic::x86_sse_ucomile_ss: 9179 case Intrinsic::x86_sse2_ucomile_sd: 9180 Opc = X86ISD::UCOMI; 9181 CC = ISD::SETLE; 9182 break; 9183 case Intrinsic::x86_sse_ucomigt_ss: 9184 case Intrinsic::x86_sse2_ucomigt_sd: 9185 Opc = X86ISD::UCOMI; 9186 CC = ISD::SETGT; 9187 break; 9188 case Intrinsic::x86_sse_ucomige_ss: 9189 case Intrinsic::x86_sse2_ucomige_sd: 9190 Opc = X86ISD::UCOMI; 9191 CC = ISD::SETGE; 9192 break; 9193 case Intrinsic::x86_sse_ucomineq_ss: 9194 case Intrinsic::x86_sse2_ucomineq_sd: 9195 Opc = X86ISD::UCOMI; 9196 CC = ISD::SETNE; 9197 break; 9198 } 9199 9200 SDValue LHS = Op.getOperand(1); 9201 SDValue RHS = Op.getOperand(2); 9202 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG); 9203 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!"); 9204 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS); 9205 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9206 DAG.getConstant(X86CC, MVT::i8), Cond); 9207 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 9208 } 9209 // ptest and testp intrinsics. The intrinsic these come from are designed to 9210 // return an integer value, not just an instruction so lower it to the ptest 9211 // or testp pattern and a setcc for the result. 9212 case Intrinsic::x86_sse41_ptestz: 9213 case Intrinsic::x86_sse41_ptestc: 9214 case Intrinsic::x86_sse41_ptestnzc: 9215 case Intrinsic::x86_avx_ptestz_256: 9216 case Intrinsic::x86_avx_ptestc_256: 9217 case Intrinsic::x86_avx_ptestnzc_256: 9218 case Intrinsic::x86_avx_vtestz_ps: 9219 case Intrinsic::x86_avx_vtestc_ps: 9220 case Intrinsic::x86_avx_vtestnzc_ps: 9221 case Intrinsic::x86_avx_vtestz_pd: 9222 case Intrinsic::x86_avx_vtestc_pd: 9223 case Intrinsic::x86_avx_vtestnzc_pd: 9224 case Intrinsic::x86_avx_vtestz_ps_256: 9225 case Intrinsic::x86_avx_vtestc_ps_256: 9226 case Intrinsic::x86_avx_vtestnzc_ps_256: 9227 case Intrinsic::x86_avx_vtestz_pd_256: 9228 case Intrinsic::x86_avx_vtestc_pd_256: 9229 case Intrinsic::x86_avx_vtestnzc_pd_256: { 9230 bool IsTestPacked = false; 9231 unsigned X86CC = 0; 9232 switch (IntNo) { 9233 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering."); 9234 case Intrinsic::x86_avx_vtestz_ps: 9235 case Intrinsic::x86_avx_vtestz_pd: 9236 case Intrinsic::x86_avx_vtestz_ps_256: 9237 case Intrinsic::x86_avx_vtestz_pd_256: 9238 IsTestPacked = true; // Fallthrough 9239 case Intrinsic::x86_sse41_ptestz: 9240 case Intrinsic::x86_avx_ptestz_256: 9241 // ZF = 1 9242 X86CC = X86::COND_E; 9243 break; 9244 case Intrinsic::x86_avx_vtestc_ps: 9245 case Intrinsic::x86_avx_vtestc_pd: 9246 case Intrinsic::x86_avx_vtestc_ps_256: 9247 case Intrinsic::x86_avx_vtestc_pd_256: 9248 IsTestPacked = true; // Fallthrough 9249 case Intrinsic::x86_sse41_ptestc: 9250 case Intrinsic::x86_avx_ptestc_256: 9251 // CF = 1 9252 X86CC = X86::COND_B; 9253 break; 9254 case Intrinsic::x86_avx_vtestnzc_ps: 9255 case Intrinsic::x86_avx_vtestnzc_pd: 9256 case Intrinsic::x86_avx_vtestnzc_ps_256: 9257 case Intrinsic::x86_avx_vtestnzc_pd_256: 9258 IsTestPacked = true; // Fallthrough 9259 case Intrinsic::x86_sse41_ptestnzc: 9260 case Intrinsic::x86_avx_ptestnzc_256: 9261 // ZF and CF = 0 9262 X86CC = X86::COND_A; 9263 break; 9264 } 9265 9266 SDValue LHS = Op.getOperand(1); 9267 SDValue RHS = Op.getOperand(2); 9268 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST; 9269 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS); 9270 SDValue CC = DAG.getConstant(X86CC, MVT::i8); 9271 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test); 9272 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 9273 } 9274 9275 // Fix vector shift instructions where the last operand is a non-immediate 9276 // i32 value. 9277 case Intrinsic::x86_sse2_pslli_w: 9278 case Intrinsic::x86_sse2_pslli_d: 9279 case Intrinsic::x86_sse2_pslli_q: 9280 case Intrinsic::x86_sse2_psrli_w: 9281 case Intrinsic::x86_sse2_psrli_d: 9282 case Intrinsic::x86_sse2_psrli_q: 9283 case Intrinsic::x86_sse2_psrai_w: 9284 case Intrinsic::x86_sse2_psrai_d: 9285 case Intrinsic::x86_mmx_pslli_w: 9286 case Intrinsic::x86_mmx_pslli_d: 9287 case Intrinsic::x86_mmx_pslli_q: 9288 case Intrinsic::x86_mmx_psrli_w: 9289 case Intrinsic::x86_mmx_psrli_d: 9290 case Intrinsic::x86_mmx_psrli_q: 9291 case Intrinsic::x86_mmx_psrai_w: 9292 case Intrinsic::x86_mmx_psrai_d: { 9293 SDValue ShAmt = Op.getOperand(2); 9294 if (isa<ConstantSDNode>(ShAmt)) 9295 return SDValue(); 9296 9297 unsigned NewIntNo = 0; 9298 EVT ShAmtVT = MVT::v4i32; 9299 switch (IntNo) { 9300 case Intrinsic::x86_sse2_pslli_w: 9301 NewIntNo = Intrinsic::x86_sse2_psll_w; 9302 break; 9303 case Intrinsic::x86_sse2_pslli_d: 9304 NewIntNo = Intrinsic::x86_sse2_psll_d; 9305 break; 9306 case Intrinsic::x86_sse2_pslli_q: 9307 NewIntNo = Intrinsic::x86_sse2_psll_q; 9308 break; 9309 case Intrinsic::x86_sse2_psrli_w: 9310 NewIntNo = Intrinsic::x86_sse2_psrl_w; 9311 break; 9312 case Intrinsic::x86_sse2_psrli_d: 9313 NewIntNo = Intrinsic::x86_sse2_psrl_d; 9314 break; 9315 case Intrinsic::x86_sse2_psrli_q: 9316 NewIntNo = Intrinsic::x86_sse2_psrl_q; 9317 break; 9318 case Intrinsic::x86_sse2_psrai_w: 9319 NewIntNo = Intrinsic::x86_sse2_psra_w; 9320 break; 9321 case Intrinsic::x86_sse2_psrai_d: 9322 NewIntNo = Intrinsic::x86_sse2_psra_d; 9323 break; 9324 default: { 9325 ShAmtVT = MVT::v2i32; 9326 switch (IntNo) { 9327 case Intrinsic::x86_mmx_pslli_w: 9328 NewIntNo = Intrinsic::x86_mmx_psll_w; 9329 break; 9330 case Intrinsic::x86_mmx_pslli_d: 9331 NewIntNo = Intrinsic::x86_mmx_psll_d; 9332 break; 9333 case Intrinsic::x86_mmx_pslli_q: 9334 NewIntNo = Intrinsic::x86_mmx_psll_q; 9335 break; 9336 case Intrinsic::x86_mmx_psrli_w: 9337 NewIntNo = Intrinsic::x86_mmx_psrl_w; 9338 break; 9339 case Intrinsic::x86_mmx_psrli_d: 9340 NewIntNo = Intrinsic::x86_mmx_psrl_d; 9341 break; 9342 case Intrinsic::x86_mmx_psrli_q: 9343 NewIntNo = Intrinsic::x86_mmx_psrl_q; 9344 break; 9345 case Intrinsic::x86_mmx_psrai_w: 9346 NewIntNo = Intrinsic::x86_mmx_psra_w; 9347 break; 9348 case Intrinsic::x86_mmx_psrai_d: 9349 NewIntNo = Intrinsic::x86_mmx_psra_d; 9350 break; 9351 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 9352 } 9353 break; 9354 } 9355 } 9356 9357 // The vector shift intrinsics with scalars uses 32b shift amounts but 9358 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 9359 // to be zero. 9360 SDValue ShOps[4]; 9361 ShOps[0] = ShAmt; 9362 ShOps[1] = DAG.getConstant(0, MVT::i32); 9363 if (ShAmtVT == MVT::v4i32) { 9364 ShOps[2] = DAG.getUNDEF(MVT::i32); 9365 ShOps[3] = DAG.getUNDEF(MVT::i32); 9366 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4); 9367 } else { 9368 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2); 9369// FIXME this must be lowered to get rid of the invalid type. 9370 } 9371 9372 EVT VT = Op.getValueType(); 9373 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt); 9374 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9375 DAG.getConstant(NewIntNo, MVT::i32), 9376 Op.getOperand(1), ShAmt); 9377 } 9378 } 9379} 9380 9381SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, 9382 SelectionDAG &DAG) const { 9383 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 9384 MFI->setReturnAddressIsTaken(true); 9385 9386 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9387 DebugLoc dl = Op.getDebugLoc(); 9388 9389 if (Depth > 0) { 9390 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 9391 SDValue Offset = 9392 DAG.getConstant(TD->getPointerSize(), 9393 Subtarget->is64Bit() ? MVT::i64 : MVT::i32); 9394 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 9395 DAG.getNode(ISD::ADD, dl, getPointerTy(), 9396 FrameAddr, Offset), 9397 MachinePointerInfo(), false, false, 0); 9398 } 9399 9400 // Just load the return address. 9401 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); 9402 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 9403 RetAddrFI, MachinePointerInfo(), false, false, 0); 9404} 9405 9406SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 9407 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 9408 MFI->setFrameAddressIsTaken(true); 9409 9410 EVT VT = Op.getValueType(); 9411 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful 9412 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9413 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP; 9414 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 9415 while (Depth--) 9416 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 9417 MachinePointerInfo(), 9418 false, false, 0); 9419 return FrameAddr; 9420} 9421 9422SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op, 9423 SelectionDAG &DAG) const { 9424 return DAG.getIntPtrConstant(2*TD->getPointerSize()); 9425} 9426 9427SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const { 9428 MachineFunction &MF = DAG.getMachineFunction(); 9429 SDValue Chain = Op.getOperand(0); 9430 SDValue Offset = Op.getOperand(1); 9431 SDValue Handler = Op.getOperand(2); 9432 DebugLoc dl = Op.getDebugLoc(); 9433 9434 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, 9435 Subtarget->is64Bit() ? X86::RBP : X86::EBP, 9436 getPointerTy()); 9437 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX); 9438 9439 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame, 9440 DAG.getIntPtrConstant(TD->getPointerSize())); 9441 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset); 9442 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(), 9443 false, false, 0); 9444 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr); 9445 MF.getRegInfo().addLiveOut(StoreAddrReg); 9446 9447 return DAG.getNode(X86ISD::EH_RETURN, dl, 9448 MVT::Other, 9449 Chain, DAG.getRegister(StoreAddrReg, getPointerTy())); 9450} 9451 9452SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 9453 SelectionDAG &DAG) const { 9454 return Op.getOperand(0); 9455} 9456 9457SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 9458 SelectionDAG &DAG) const { 9459 SDValue Root = Op.getOperand(0); 9460 SDValue Trmp = Op.getOperand(1); // trampoline 9461 SDValue FPtr = Op.getOperand(2); // nested function 9462 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 9463 DebugLoc dl = Op.getDebugLoc(); 9464 9465 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 9466 9467 if (Subtarget->is64Bit()) { 9468 SDValue OutChains[6]; 9469 9470 // Large code-model. 9471 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode. 9472 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode. 9473 9474 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10); 9475 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11); 9476 9477 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix 9478 9479 // Load the pointer to the nested function into R11. 9480 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11 9481 SDValue Addr = Trmp; 9482 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 9483 Addr, MachinePointerInfo(TrmpAddr), 9484 false, false, 0); 9485 9486 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9487 DAG.getConstant(2, MVT::i64)); 9488 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, 9489 MachinePointerInfo(TrmpAddr, 2), 9490 false, false, 2); 9491 9492 // Load the 'nest' parameter value into R10. 9493 // R10 is specified in X86CallingConv.td 9494 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10 9495 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9496 DAG.getConstant(10, MVT::i64)); 9497 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 9498 Addr, MachinePointerInfo(TrmpAddr, 10), 9499 false, false, 0); 9500 9501 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9502 DAG.getConstant(12, MVT::i64)); 9503 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, 9504 MachinePointerInfo(TrmpAddr, 12), 9505 false, false, 2); 9506 9507 // Jump to the nested function. 9508 OpCode = (JMP64r << 8) | REX_WB; // jmpq *... 9509 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9510 DAG.getConstant(20, MVT::i64)); 9511 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 9512 Addr, MachinePointerInfo(TrmpAddr, 20), 9513 false, false, 0); 9514 9515 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11 9516 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9517 DAG.getConstant(22, MVT::i64)); 9518 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr, 9519 MachinePointerInfo(TrmpAddr, 22), 9520 false, false, 0); 9521 9522 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6); 9523 } else { 9524 const Function *Func = 9525 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue()); 9526 CallingConv::ID CC = Func->getCallingConv(); 9527 unsigned NestReg; 9528 9529 switch (CC) { 9530 default: 9531 llvm_unreachable("Unsupported calling convention"); 9532 case CallingConv::C: 9533 case CallingConv::X86_StdCall: { 9534 // Pass 'nest' parameter in ECX. 9535 // Must be kept in sync with X86CallingConv.td 9536 NestReg = X86::ECX; 9537 9538 // Check that ECX wasn't needed by an 'inreg' parameter. 9539 FunctionType *FTy = Func->getFunctionType(); 9540 const AttrListPtr &Attrs = Func->getAttributes(); 9541 9542 if (!Attrs.isEmpty() && !Func->isVarArg()) { 9543 unsigned InRegCount = 0; 9544 unsigned Idx = 1; 9545 9546 for (FunctionType::param_iterator I = FTy->param_begin(), 9547 E = FTy->param_end(); I != E; ++I, ++Idx) 9548 if (Attrs.paramHasAttr(Idx, Attribute::InReg)) 9549 // FIXME: should only count parameters that are lowered to integers. 9550 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32; 9551 9552 if (InRegCount > 2) { 9553 report_fatal_error("Nest register in use - reduce number of inreg" 9554 " parameters!"); 9555 } 9556 } 9557 break; 9558 } 9559 case CallingConv::X86_FastCall: 9560 case CallingConv::X86_ThisCall: 9561 case CallingConv::Fast: 9562 // Pass 'nest' parameter in EAX. 9563 // Must be kept in sync with X86CallingConv.td 9564 NestReg = X86::EAX; 9565 break; 9566 } 9567 9568 SDValue OutChains[4]; 9569 SDValue Addr, Disp; 9570 9571 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9572 DAG.getConstant(10, MVT::i32)); 9573 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr); 9574 9575 // This is storing the opcode for MOV32ri. 9576 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte. 9577 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg); 9578 OutChains[0] = DAG.getStore(Root, dl, 9579 DAG.getConstant(MOV32ri|N86Reg, MVT::i8), 9580 Trmp, MachinePointerInfo(TrmpAddr), 9581 false, false, 0); 9582 9583 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9584 DAG.getConstant(1, MVT::i32)); 9585 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, 9586 MachinePointerInfo(TrmpAddr, 1), 9587 false, false, 1); 9588 9589 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode. 9590 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9591 DAG.getConstant(5, MVT::i32)); 9592 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr, 9593 MachinePointerInfo(TrmpAddr, 5), 9594 false, false, 1); 9595 9596 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9597 DAG.getConstant(6, MVT::i32)); 9598 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, 9599 MachinePointerInfo(TrmpAddr, 6), 9600 false, false, 1); 9601 9602 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4); 9603 } 9604} 9605 9606SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 9607 SelectionDAG &DAG) const { 9608 /* 9609 The rounding mode is in bits 11:10 of FPSR, and has the following 9610 settings: 9611 00 Round to nearest 9612 01 Round to -inf 9613 10 Round to +inf 9614 11 Round to 0 9615 9616 FLT_ROUNDS, on the other hand, expects the following: 9617 -1 Undefined 9618 0 Round to 0 9619 1 Round to nearest 9620 2 Round to +inf 9621 3 Round to -inf 9622 9623 To perform the conversion, we do: 9624 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3) 9625 */ 9626 9627 MachineFunction &MF = DAG.getMachineFunction(); 9628 const TargetMachine &TM = MF.getTarget(); 9629 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 9630 unsigned StackAlignment = TFI.getStackAlignment(); 9631 EVT VT = Op.getValueType(); 9632 DebugLoc DL = Op.getDebugLoc(); 9633 9634 // Save FP Control Word to stack slot 9635 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false); 9636 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 9637 9638 9639 MachineMemOperand *MMO = 9640 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 9641 MachineMemOperand::MOStore, 2, 2); 9642 9643 SDValue Ops[] = { DAG.getEntryNode(), StackSlot }; 9644 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL, 9645 DAG.getVTList(MVT::Other), 9646 Ops, 2, MVT::i16, MMO); 9647 9648 // Load FP Control Word from stack slot 9649 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, 9650 MachinePointerInfo(), false, false, 0); 9651 9652 // Transform as necessary 9653 SDValue CWD1 = 9654 DAG.getNode(ISD::SRL, DL, MVT::i16, 9655 DAG.getNode(ISD::AND, DL, MVT::i16, 9656 CWD, DAG.getConstant(0x800, MVT::i16)), 9657 DAG.getConstant(11, MVT::i8)); 9658 SDValue CWD2 = 9659 DAG.getNode(ISD::SRL, DL, MVT::i16, 9660 DAG.getNode(ISD::AND, DL, MVT::i16, 9661 CWD, DAG.getConstant(0x400, MVT::i16)), 9662 DAG.getConstant(9, MVT::i8)); 9663 9664 SDValue RetVal = 9665 DAG.getNode(ISD::AND, DL, MVT::i16, 9666 DAG.getNode(ISD::ADD, DL, MVT::i16, 9667 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2), 9668 DAG.getConstant(1, MVT::i16)), 9669 DAG.getConstant(3, MVT::i16)); 9670 9671 9672 return DAG.getNode((VT.getSizeInBits() < 16 ? 9673 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal); 9674} 9675 9676SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const { 9677 EVT VT = Op.getValueType(); 9678 EVT OpVT = VT; 9679 unsigned NumBits = VT.getSizeInBits(); 9680 DebugLoc dl = Op.getDebugLoc(); 9681 9682 Op = Op.getOperand(0); 9683 if (VT == MVT::i8) { 9684 // Zero extend to i32 since there is not an i8 bsr. 9685 OpVT = MVT::i32; 9686 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 9687 } 9688 9689 // Issue a bsr (scan bits in reverse) which also sets EFLAGS. 9690 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 9691 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 9692 9693 // If src is zero (i.e. bsr sets ZF), returns NumBits. 9694 SDValue Ops[] = { 9695 Op, 9696 DAG.getConstant(NumBits+NumBits-1, OpVT), 9697 DAG.getConstant(X86::COND_E, MVT::i8), 9698 Op.getValue(1) 9699 }; 9700 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 9701 9702 // Finally xor with NumBits-1. 9703 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 9704 9705 if (VT == MVT::i8) 9706 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 9707 return Op; 9708} 9709 9710SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const { 9711 EVT VT = Op.getValueType(); 9712 EVT OpVT = VT; 9713 unsigned NumBits = VT.getSizeInBits(); 9714 DebugLoc dl = Op.getDebugLoc(); 9715 9716 Op = Op.getOperand(0); 9717 if (VT == MVT::i8) { 9718 OpVT = MVT::i32; 9719 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 9720 } 9721 9722 // Issue a bsf (scan bits forward) which also sets EFLAGS. 9723 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 9724 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); 9725 9726 // If src is zero (i.e. bsf sets ZF), returns NumBits. 9727 SDValue Ops[] = { 9728 Op, 9729 DAG.getConstant(NumBits, OpVT), 9730 DAG.getConstant(X86::COND_E, MVT::i8), 9731 Op.getValue(1) 9732 }; 9733 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 9734 9735 if (VT == MVT::i8) 9736 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 9737 return Op; 9738} 9739 9740// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit 9741// ones, and then concatenate the result back. 9742static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) { 9743 EVT VT = Op.getValueType(); 9744 9745 assert(VT.getSizeInBits() == 256 && VT.isInteger() && 9746 "Unsupported value type for operation"); 9747 9748 int NumElems = VT.getVectorNumElements(); 9749 DebugLoc dl = Op.getDebugLoc(); 9750 SDValue Idx0 = DAG.getConstant(0, MVT::i32); 9751 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32); 9752 9753 // Extract the LHS vectors 9754 SDValue LHS = Op.getOperand(0); 9755 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl); 9756 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl); 9757 9758 // Extract the RHS vectors 9759 SDValue RHS = Op.getOperand(1); 9760 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl); 9761 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl); 9762 9763 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 9764 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 9765 9766 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 9767 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1), 9768 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2)); 9769} 9770 9771SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const { 9772 assert(Op.getValueType().getSizeInBits() == 256 && 9773 Op.getValueType().isInteger() && 9774 "Only handle AVX 256-bit vector integer operation"); 9775 return Lower256IntArith(Op, DAG); 9776} 9777 9778SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const { 9779 assert(Op.getValueType().getSizeInBits() == 256 && 9780 Op.getValueType().isInteger() && 9781 "Only handle AVX 256-bit vector integer operation"); 9782 return Lower256IntArith(Op, DAG); 9783} 9784 9785SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9786 EVT VT = Op.getValueType(); 9787 9788 // Decompose 256-bit ops into smaller 128-bit ops. 9789 if (VT.getSizeInBits() == 256) 9790 return Lower256IntArith(Op, DAG); 9791 9792 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply"); 9793 DebugLoc dl = Op.getDebugLoc(); 9794 9795 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32); 9796 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32); 9797 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b ); 9798 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi ); 9799 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b ); 9800 // 9801 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 ); 9802 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 ); 9803 // return AloBlo + AloBhi + AhiBlo; 9804 9805 SDValue A = Op.getOperand(0); 9806 SDValue B = Op.getOperand(1); 9807 9808 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9809 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 9810 A, DAG.getConstant(32, MVT::i32)); 9811 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9812 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 9813 B, DAG.getConstant(32, MVT::i32)); 9814 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9815 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 9816 A, B); 9817 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9818 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 9819 A, Bhi); 9820 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9821 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 9822 Ahi, B); 9823 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9824 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 9825 AloBhi, DAG.getConstant(32, MVT::i32)); 9826 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9827 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 9828 AhiBlo, DAG.getConstant(32, MVT::i32)); 9829 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 9830 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 9831 return Res; 9832} 9833 9834SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const { 9835 9836 EVT VT = Op.getValueType(); 9837 DebugLoc dl = Op.getDebugLoc(); 9838 SDValue R = Op.getOperand(0); 9839 SDValue Amt = Op.getOperand(1); 9840 LLVMContext *Context = DAG.getContext(); 9841 9842 if (!(Subtarget->hasSSE2() || Subtarget->hasAVX())) 9843 return SDValue(); 9844 9845 // Decompose 256-bit shifts into smaller 128-bit shifts. 9846 if (VT.getSizeInBits() == 256) { 9847 int NumElems = VT.getVectorNumElements(); 9848 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 9849 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 9850 9851 // Extract the two vectors 9852 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl); 9853 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32), 9854 DAG, dl); 9855 9856 // Recreate the shift amount vectors 9857 SDValue Amt1, Amt2; 9858 if (Amt.getOpcode() == ISD::BUILD_VECTOR) { 9859 // Constant shift amount 9860 SmallVector<SDValue, 4> Amt1Csts; 9861 SmallVector<SDValue, 4> Amt2Csts; 9862 for (int i = 0; i < NumElems/2; ++i) 9863 Amt1Csts.push_back(Amt->getOperand(i)); 9864 for (int i = NumElems/2; i < NumElems; ++i) 9865 Amt2Csts.push_back(Amt->getOperand(i)); 9866 9867 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 9868 &Amt1Csts[0], NumElems/2); 9869 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 9870 &Amt2Csts[0], NumElems/2); 9871 } else { 9872 // Variable shift amount 9873 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl); 9874 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32), 9875 DAG, dl); 9876 } 9877 9878 // Issue new vector shifts for the smaller types 9879 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1); 9880 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2); 9881 9882 // Concatenate the result back 9883 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2); 9884 } 9885 9886 // Optimize shl/srl/sra with constant shift amount. 9887 if (isSplatVector(Amt.getNode())) { 9888 SDValue SclrAmt = Amt->getOperand(0); 9889 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) { 9890 uint64_t ShiftAmt = C->getZExtValue(); 9891 9892 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL) 9893 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9894 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 9895 R, DAG.getConstant(ShiftAmt, MVT::i32)); 9896 9897 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL) 9898 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9899 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 9900 R, DAG.getConstant(ShiftAmt, MVT::i32)); 9901 9902 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL) 9903 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9904 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 9905 R, DAG.getConstant(ShiftAmt, MVT::i32)); 9906 9907 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL) 9908 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9909 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 9910 R, DAG.getConstant(ShiftAmt, MVT::i32)); 9911 9912 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL) 9913 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9914 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32), 9915 R, DAG.getConstant(ShiftAmt, MVT::i32)); 9916 9917 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL) 9918 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9919 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 9920 R, DAG.getConstant(ShiftAmt, MVT::i32)); 9921 9922 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA) 9923 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9924 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32), 9925 R, DAG.getConstant(ShiftAmt, MVT::i32)); 9926 9927 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA) 9928 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9929 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32), 9930 R, DAG.getConstant(ShiftAmt, MVT::i32)); 9931 } 9932 } 9933 9934 // Lower SHL with variable shift amount. 9935 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) { 9936 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9937 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 9938 Op.getOperand(1), DAG.getConstant(23, MVT::i32)); 9939 9940 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U)); 9941 9942 std::vector<Constant*> CV(4, CI); 9943 Constant *C = ConstantVector::get(CV); 9944 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 9945 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 9946 MachinePointerInfo::getConstantPool(), 9947 false, false, 16); 9948 9949 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend); 9950 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op); 9951 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op); 9952 return DAG.getNode(ISD::MUL, dl, VT, Op, R); 9953 } 9954 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) { 9955 // a = a << 5; 9956 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9957 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 9958 Op.getOperand(1), DAG.getConstant(5, MVT::i32)); 9959 9960 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15)); 9961 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63)); 9962 9963 std::vector<Constant*> CVM1(16, CM1); 9964 std::vector<Constant*> CVM2(16, CM2); 9965 Constant *C = ConstantVector::get(CVM1); 9966 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 9967 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 9968 MachinePointerInfo::getConstantPool(), 9969 false, false, 16); 9970 9971 // r = pblendv(r, psllw(r & (char16)15, 4), a); 9972 M = DAG.getNode(ISD::AND, dl, VT, R, M); 9973 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9974 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 9975 DAG.getConstant(4, MVT::i32)); 9976 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op); 9977 // a += a 9978 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 9979 9980 C = ConstantVector::get(CVM2); 9981 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 9982 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 9983 MachinePointerInfo::getConstantPool(), 9984 false, false, 16); 9985 9986 // r = pblendv(r, psllw(r & (char16)63, 2), a); 9987 M = DAG.getNode(ISD::AND, dl, VT, R, M); 9988 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9989 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 9990 DAG.getConstant(2, MVT::i32)); 9991 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op); 9992 // a += a 9993 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 9994 9995 // return pblendv(r, r+r, a); 9996 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, 9997 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op); 9998 return R; 9999 } 10000 return SDValue(); 10001} 10002 10003SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 10004 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus 10005 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering 10006 // looks for this combo and may remove the "setcc" instruction if the "setcc" 10007 // has only one use. 10008 SDNode *N = Op.getNode(); 10009 SDValue LHS = N->getOperand(0); 10010 SDValue RHS = N->getOperand(1); 10011 unsigned BaseOp = 0; 10012 unsigned Cond = 0; 10013 DebugLoc DL = Op.getDebugLoc(); 10014 switch (Op.getOpcode()) { 10015 default: llvm_unreachable("Unknown ovf instruction!"); 10016 case ISD::SADDO: 10017 // A subtract of one will be selected as a INC. Note that INC doesn't 10018 // set CF, so we can't do this for UADDO. 10019 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 10020 if (C->isOne()) { 10021 BaseOp = X86ISD::INC; 10022 Cond = X86::COND_O; 10023 break; 10024 } 10025 BaseOp = X86ISD::ADD; 10026 Cond = X86::COND_O; 10027 break; 10028 case ISD::UADDO: 10029 BaseOp = X86ISD::ADD; 10030 Cond = X86::COND_B; 10031 break; 10032 case ISD::SSUBO: 10033 // A subtract of one will be selected as a DEC. Note that DEC doesn't 10034 // set CF, so we can't do this for USUBO. 10035 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 10036 if (C->isOne()) { 10037 BaseOp = X86ISD::DEC; 10038 Cond = X86::COND_O; 10039 break; 10040 } 10041 BaseOp = X86ISD::SUB; 10042 Cond = X86::COND_O; 10043 break; 10044 case ISD::USUBO: 10045 BaseOp = X86ISD::SUB; 10046 Cond = X86::COND_B; 10047 break; 10048 case ISD::SMULO: 10049 BaseOp = X86ISD::SMUL; 10050 Cond = X86::COND_O; 10051 break; 10052 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs 10053 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0), 10054 MVT::i32); 10055 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS); 10056 10057 SDValue SetCC = 10058 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 10059 DAG.getConstant(X86::COND_O, MVT::i32), 10060 SDValue(Sum.getNode(), 2)); 10061 10062 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 10063 } 10064 } 10065 10066 // Also sets EFLAGS. 10067 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 10068 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 10069 10070 SDValue SetCC = 10071 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1), 10072 DAG.getConstant(Cond, MVT::i32), 10073 SDValue(Sum.getNode(), 1)); 10074 10075 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 10076} 10077 10078SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{ 10079 DebugLoc dl = Op.getDebugLoc(); 10080 SDNode* Node = Op.getNode(); 10081 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 10082 EVT VT = Node->getValueType(0); 10083 if (Subtarget->hasSSE2() && VT.isVector()) { 10084 unsigned BitsDiff = VT.getScalarType().getSizeInBits() - 10085 ExtraVT.getScalarType().getSizeInBits(); 10086 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32); 10087 10088 unsigned SHLIntrinsicsID = 0; 10089 unsigned SRAIntrinsicsID = 0; 10090 switch (VT.getSimpleVT().SimpleTy) { 10091 default: 10092 return SDValue(); 10093 case MVT::v2i64: { 10094 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q; 10095 SRAIntrinsicsID = 0; 10096 break; 10097 } 10098 case MVT::v4i32: { 10099 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d; 10100 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d; 10101 break; 10102 } 10103 case MVT::v8i16: { 10104 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w; 10105 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w; 10106 break; 10107 } 10108 } 10109 10110 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10111 DAG.getConstant(SHLIntrinsicsID, MVT::i32), 10112 Node->getOperand(0), ShAmt); 10113 10114 // In case of 1 bit sext, no need to shr 10115 if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1; 10116 10117 if (SRAIntrinsicsID) { 10118 Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10119 DAG.getConstant(SRAIntrinsicsID, MVT::i32), 10120 Tmp1, ShAmt); 10121 } 10122 return Tmp1; 10123 } 10124 10125 return SDValue(); 10126} 10127 10128 10129SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{ 10130 DebugLoc dl = Op.getDebugLoc(); 10131 10132 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2. 10133 // There isn't any reason to disable it if the target processor supports it. 10134 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) { 10135 SDValue Chain = Op.getOperand(0); 10136 SDValue Zero = DAG.getConstant(0, MVT::i32); 10137 SDValue Ops[] = { 10138 DAG.getRegister(X86::ESP, MVT::i32), // Base 10139 DAG.getTargetConstant(1, MVT::i8), // Scale 10140 DAG.getRegister(0, MVT::i32), // Index 10141 DAG.getTargetConstant(0, MVT::i32), // Disp 10142 DAG.getRegister(0, MVT::i32), // Segment. 10143 Zero, 10144 Chain 10145 }; 10146 SDNode *Res = 10147 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 10148 array_lengthof(Ops)); 10149 return SDValue(Res, 0); 10150 } 10151 10152 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 10153 if (!isDev) 10154 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 10155 10156 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 10157 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 10158 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 10159 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 10160 10161 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>; 10162 if (!Op1 && !Op2 && !Op3 && Op4) 10163 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0)); 10164 10165 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>; 10166 if (Op1 && !Op2 && !Op3 && !Op4) 10167 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0)); 10168 10169 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 10170 // (MFENCE)>; 10171 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 10172} 10173 10174SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op, 10175 SelectionDAG &DAG) const { 10176 DebugLoc dl = Op.getDebugLoc(); 10177 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>( 10178 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()); 10179 SynchronizationScope FenceScope = static_cast<SynchronizationScope>( 10180 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 10181 10182 // The only fence that needs an instruction is a sequentially-consistent 10183 // cross-thread fence. 10184 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) { 10185 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for 10186 // no-sse2). There isn't any reason to disable it if the target processor 10187 // supports it. 10188 if (Subtarget->hasSSE2() || Subtarget->is64Bit()) 10189 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 10190 10191 SDValue Chain = Op.getOperand(0); 10192 SDValue Zero = DAG.getConstant(0, MVT::i32); 10193 SDValue Ops[] = { 10194 DAG.getRegister(X86::ESP, MVT::i32), // Base 10195 DAG.getTargetConstant(1, MVT::i8), // Scale 10196 DAG.getRegister(0, MVT::i32), // Index 10197 DAG.getTargetConstant(0, MVT::i32), // Disp 10198 DAG.getRegister(0, MVT::i32), // Segment. 10199 Zero, 10200 Chain 10201 }; 10202 SDNode *Res = 10203 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 10204 array_lengthof(Ops)); 10205 return SDValue(Res, 0); 10206 } 10207 10208 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 10209 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 10210} 10211 10212 10213SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 10214 EVT T = Op.getValueType(); 10215 DebugLoc DL = Op.getDebugLoc(); 10216 unsigned Reg = 0; 10217 unsigned size = 0; 10218 switch(T.getSimpleVT().SimpleTy) { 10219 default: 10220 assert(false && "Invalid value type!"); 10221 case MVT::i8: Reg = X86::AL; size = 1; break; 10222 case MVT::i16: Reg = X86::AX; size = 2; break; 10223 case MVT::i32: Reg = X86::EAX; size = 4; break; 10224 case MVT::i64: 10225 assert(Subtarget->is64Bit() && "Node not type legal!"); 10226 Reg = X86::RAX; size = 8; 10227 break; 10228 } 10229 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg, 10230 Op.getOperand(2), SDValue()); 10231 SDValue Ops[] = { cpIn.getValue(0), 10232 Op.getOperand(1), 10233 Op.getOperand(3), 10234 DAG.getTargetConstant(size, MVT::i8), 10235 cpIn.getValue(1) }; 10236 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10237 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand(); 10238 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys, 10239 Ops, 5, T, MMO); 10240 SDValue cpOut = 10241 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1)); 10242 return cpOut; 10243} 10244 10245SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op, 10246 SelectionDAG &DAG) const { 10247 assert(Subtarget->is64Bit() && "Result not type legalized?"); 10248 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10249 SDValue TheChain = Op.getOperand(0); 10250 DebugLoc dl = Op.getDebugLoc(); 10251 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 10252 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1)); 10253 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64, 10254 rax.getValue(2)); 10255 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx, 10256 DAG.getConstant(32, MVT::i8)); 10257 SDValue Ops[] = { 10258 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp), 10259 rdx.getValue(1) 10260 }; 10261 return DAG.getMergeValues(Ops, 2, dl); 10262} 10263 10264SDValue X86TargetLowering::LowerBITCAST(SDValue Op, 10265 SelectionDAG &DAG) const { 10266 EVT SrcVT = Op.getOperand(0).getValueType(); 10267 EVT DstVT = Op.getValueType(); 10268 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() && 10269 Subtarget->hasMMX() && "Unexpected custom BITCAST"); 10270 assert((DstVT == MVT::i64 || 10271 (DstVT.isVector() && DstVT.getSizeInBits()==64)) && 10272 "Unexpected custom BITCAST"); 10273 // i64 <=> MMX conversions are Legal. 10274 if (SrcVT==MVT::i64 && DstVT.isVector()) 10275 return Op; 10276 if (DstVT==MVT::i64 && SrcVT.isVector()) 10277 return Op; 10278 // MMX <=> MMX conversions are Legal. 10279 if (SrcVT.isVector() && DstVT.isVector()) 10280 return Op; 10281 // All other conversions need to be expanded. 10282 return SDValue(); 10283} 10284 10285SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const { 10286 SDNode *Node = Op.getNode(); 10287 DebugLoc dl = Node->getDebugLoc(); 10288 EVT T = Node->getValueType(0); 10289 SDValue negOp = DAG.getNode(ISD::SUB, dl, T, 10290 DAG.getConstant(0, T), Node->getOperand(2)); 10291 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, 10292 cast<AtomicSDNode>(Node)->getMemoryVT(), 10293 Node->getOperand(0), 10294 Node->getOperand(1), negOp, 10295 cast<AtomicSDNode>(Node)->getSrcValue(), 10296 cast<AtomicSDNode>(Node)->getAlignment(), 10297 cast<AtomicSDNode>(Node)->getOrdering(), 10298 cast<AtomicSDNode>(Node)->getSynchScope()); 10299} 10300 10301static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) { 10302 SDNode *Node = Op.getNode(); 10303 DebugLoc dl = Node->getDebugLoc(); 10304 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 10305 10306 // Convert seq_cst store -> xchg 10307 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b) 10308 // FIXME: On 32-bit, store -> fist or movq would be more efficient 10309 // (The only way to get a 16-byte store is cmpxchg16b) 10310 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment. 10311 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent || 10312 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10313 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 10314 cast<AtomicSDNode>(Node)->getMemoryVT(), 10315 Node->getOperand(0), 10316 Node->getOperand(1), Node->getOperand(2), 10317 cast<AtomicSDNode>(Node)->getMemOperand(), 10318 cast<AtomicSDNode>(Node)->getOrdering(), 10319 cast<AtomicSDNode>(Node)->getSynchScope()); 10320 return Swap.getValue(1); 10321 } 10322 // Other atomic stores have a simple pattern. 10323 return Op; 10324} 10325 10326static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 10327 EVT VT = Op.getNode()->getValueType(0); 10328 10329 // Let legalize expand this if it isn't a legal type yet. 10330 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10331 return SDValue(); 10332 10333 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 10334 10335 unsigned Opc; 10336 bool ExtraOp = false; 10337 switch (Op.getOpcode()) { 10338 default: assert(0 && "Invalid code"); 10339 case ISD::ADDC: Opc = X86ISD::ADD; break; 10340 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break; 10341 case ISD::SUBC: Opc = X86ISD::SUB; break; 10342 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break; 10343 } 10344 10345 if (!ExtraOp) 10346 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 10347 Op.getOperand(1)); 10348 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 10349 Op.getOperand(1), Op.getOperand(2)); 10350} 10351 10352/// LowerOperation - Provide custom lowering hooks for some operations. 10353/// 10354SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10355 switch (Op.getOpcode()) { 10356 default: llvm_unreachable("Should not custom lower this!"); 10357 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG); 10358 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG); 10359 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG); 10360 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG); 10361 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG); 10362 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG); 10363 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10364 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 10365 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10366 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10367 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10368 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG); 10369 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG); 10370 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10371 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10372 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10373 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10374 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); 10375 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10376 case ISD::SHL_PARTS: 10377 case ISD::SRA_PARTS: 10378 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG); 10379 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 10380 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG); 10381 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 10382 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG); 10383 case ISD::FABS: return LowerFABS(Op, DAG); 10384 case ISD::FNEG: return LowerFNEG(Op, DAG); 10385 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 10386 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG); 10387 case ISD::SETCC: return LowerSETCC(Op, DAG); 10388 case ISD::SELECT: return LowerSELECT(Op, DAG); 10389 case ISD::VSELECT: return LowerVSELECT(Op, DAG); 10390 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 10391 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10392 case ISD::VASTART: return LowerVASTART(Op, DAG); 10393 case ISD::VAARG: return LowerVAARG(Op, DAG); 10394 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10395 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10396 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10397 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10398 case ISD::FRAME_TO_ARGS_OFFSET: 10399 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG); 10400 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10401 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG); 10402 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10403 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10404 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10405 case ISD::CTLZ: return LowerCTLZ(Op, DAG); 10406 case ISD::CTTZ: return LowerCTTZ(Op, DAG); 10407 case ISD::MUL: return LowerMUL(Op, DAG); 10408 case ISD::SRA: 10409 case ISD::SRL: 10410 case ISD::SHL: return LowerShift(Op, DAG); 10411 case ISD::SADDO: 10412 case ISD::UADDO: 10413 case ISD::SSUBO: 10414 case ISD::USUBO: 10415 case ISD::SMULO: 10416 case ISD::UMULO: return LowerXALUO(Op, DAG); 10417 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG); 10418 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10419 case ISD::ADDC: 10420 case ISD::ADDE: 10421 case ISD::SUBC: 10422 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 10423 case ISD::ADD: return LowerADD(Op, DAG); 10424 case ISD::SUB: return LowerSUB(Op, DAG); 10425 } 10426} 10427 10428static void ReplaceATOMIC_LOAD(SDNode *Node, 10429 SmallVectorImpl<SDValue> &Results, 10430 SelectionDAG &DAG) { 10431 DebugLoc dl = Node->getDebugLoc(); 10432 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 10433 10434 // Convert wide load -> cmpxchg8b/cmpxchg16b 10435 // FIXME: On 32-bit, load -> fild or movq would be more efficient 10436 // (The only way to get a 16-byte load is cmpxchg16b) 10437 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment. 10438 SDValue Zero = DAG.getConstant(0, VT); 10439 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT, 10440 Node->getOperand(0), 10441 Node->getOperand(1), Zero, Zero, 10442 cast<AtomicSDNode>(Node)->getMemOperand(), 10443 cast<AtomicSDNode>(Node)->getOrdering(), 10444 cast<AtomicSDNode>(Node)->getSynchScope()); 10445 Results.push_back(Swap.getValue(0)); 10446 Results.push_back(Swap.getValue(1)); 10447} 10448 10449void X86TargetLowering:: 10450ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results, 10451 SelectionDAG &DAG, unsigned NewOp) const { 10452 EVT T = Node->getValueType(0); 10453 DebugLoc dl = Node->getDebugLoc(); 10454 assert (T == MVT::i64 && "Only know how to expand i64 atomics"); 10455 10456 SDValue Chain = Node->getOperand(0); 10457 SDValue In1 = Node->getOperand(1); 10458 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 10459 Node->getOperand(2), DAG.getIntPtrConstant(0)); 10460 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 10461 Node->getOperand(2), DAG.getIntPtrConstant(1)); 10462 SDValue Ops[] = { Chain, In1, In2L, In2H }; 10463 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10464 SDValue Result = 10465 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64, 10466 cast<MemSDNode>(Node)->getMemOperand()); 10467 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)}; 10468 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 10469 Results.push_back(Result.getValue(2)); 10470} 10471 10472/// ReplaceNodeResults - Replace a node with an illegal result type 10473/// with a new node built out of custom code. 10474void X86TargetLowering::ReplaceNodeResults(SDNode *N, 10475 SmallVectorImpl<SDValue>&Results, 10476 SelectionDAG &DAG) const { 10477 DebugLoc dl = N->getDebugLoc(); 10478 switch (N->getOpcode()) { 10479 default: 10480 assert(false && "Do not know how to custom type legalize this operation!"); 10481 return; 10482 case ISD::SIGN_EXTEND_INREG: 10483 case ISD::ADDC: 10484 case ISD::ADDE: 10485 case ISD::SUBC: 10486 case ISD::SUBE: 10487 // We don't want to expand or promote these. 10488 return; 10489 case ISD::FP_TO_SINT: { 10490 std::pair<SDValue,SDValue> Vals = 10491 FP_TO_INTHelper(SDValue(N, 0), DAG, true); 10492 SDValue FIST = Vals.first, StackSlot = Vals.second; 10493 if (FIST.getNode() != 0) { 10494 EVT VT = N->getValueType(0); 10495 // Return a load from the stack slot. 10496 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, 10497 MachinePointerInfo(), false, false, 0)); 10498 } 10499 return; 10500 } 10501 case ISD::READCYCLECOUNTER: { 10502 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10503 SDValue TheChain = N->getOperand(0); 10504 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 10505 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32, 10506 rd.getValue(1)); 10507 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32, 10508 eax.getValue(2)); 10509 // Use a buildpair to merge the two 32-bit values into a 64-bit one. 10510 SDValue Ops[] = { eax, edx }; 10511 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2)); 10512 Results.push_back(edx.getValue(1)); 10513 return; 10514 } 10515 case ISD::ATOMIC_CMP_SWAP: { 10516 EVT T = N->getValueType(0); 10517 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair"); 10518 bool Regs64bit = T == MVT::i128; 10519 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32; 10520 SDValue cpInL, cpInH; 10521 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 10522 DAG.getConstant(0, HalfT)); 10523 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 10524 DAG.getConstant(1, HalfT)); 10525 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, 10526 Regs64bit ? X86::RAX : X86::EAX, 10527 cpInL, SDValue()); 10528 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, 10529 Regs64bit ? X86::RDX : X86::EDX, 10530 cpInH, cpInL.getValue(1)); 10531 SDValue swapInL, swapInH; 10532 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 10533 DAG.getConstant(0, HalfT)); 10534 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 10535 DAG.getConstant(1, HalfT)); 10536 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, 10537 Regs64bit ? X86::RBX : X86::EBX, 10538 swapInL, cpInH.getValue(1)); 10539 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, 10540 Regs64bit ? X86::RCX : X86::ECX, 10541 swapInH, swapInL.getValue(1)); 10542 SDValue Ops[] = { swapInH.getValue(0), 10543 N->getOperand(1), 10544 swapInH.getValue(1) }; 10545 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10546 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 10547 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG : 10548 X86ISD::LCMPXCHG8_DAG; 10549 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, 10550 Ops, 3, T, MMO); 10551 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, 10552 Regs64bit ? X86::RAX : X86::EAX, 10553 HalfT, Result.getValue(1)); 10554 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, 10555 Regs64bit ? X86::RDX : X86::EDX, 10556 HalfT, cpOutL.getValue(2)); 10557 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)}; 10558 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2)); 10559 Results.push_back(cpOutH.getValue(1)); 10560 return; 10561 } 10562 case ISD::ATOMIC_LOAD_ADD: 10563 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG); 10564 return; 10565 case ISD::ATOMIC_LOAD_AND: 10566 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG); 10567 return; 10568 case ISD::ATOMIC_LOAD_NAND: 10569 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG); 10570 return; 10571 case ISD::ATOMIC_LOAD_OR: 10572 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG); 10573 return; 10574 case ISD::ATOMIC_LOAD_SUB: 10575 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG); 10576 return; 10577 case ISD::ATOMIC_LOAD_XOR: 10578 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG); 10579 return; 10580 case ISD::ATOMIC_SWAP: 10581 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG); 10582 return; 10583 case ISD::ATOMIC_LOAD: 10584 ReplaceATOMIC_LOAD(N, Results, DAG); 10585 } 10586} 10587 10588const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const { 10589 switch (Opcode) { 10590 default: return NULL; 10591 case X86ISD::BSF: return "X86ISD::BSF"; 10592 case X86ISD::BSR: return "X86ISD::BSR"; 10593 case X86ISD::SHLD: return "X86ISD::SHLD"; 10594 case X86ISD::SHRD: return "X86ISD::SHRD"; 10595 case X86ISD::FAND: return "X86ISD::FAND"; 10596 case X86ISD::FOR: return "X86ISD::FOR"; 10597 case X86ISD::FXOR: return "X86ISD::FXOR"; 10598 case X86ISD::FSRL: return "X86ISD::FSRL"; 10599 case X86ISD::FILD: return "X86ISD::FILD"; 10600 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG"; 10601 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM"; 10602 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM"; 10603 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM"; 10604 case X86ISD::FLD: return "X86ISD::FLD"; 10605 case X86ISD::FST: return "X86ISD::FST"; 10606 case X86ISD::CALL: return "X86ISD::CALL"; 10607 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG"; 10608 case X86ISD::BT: return "X86ISD::BT"; 10609 case X86ISD::CMP: return "X86ISD::CMP"; 10610 case X86ISD::COMI: return "X86ISD::COMI"; 10611 case X86ISD::UCOMI: return "X86ISD::UCOMI"; 10612 case X86ISD::SETCC: return "X86ISD::SETCC"; 10613 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY"; 10614 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd"; 10615 case X86ISD::FSETCCss: return "X86ISD::FSETCCss"; 10616 case X86ISD::CMOV: return "X86ISD::CMOV"; 10617 case X86ISD::BRCOND: return "X86ISD::BRCOND"; 10618 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG"; 10619 case X86ISD::REP_STOS: return "X86ISD::REP_STOS"; 10620 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS"; 10621 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg"; 10622 case X86ISD::Wrapper: return "X86ISD::Wrapper"; 10623 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP"; 10624 case X86ISD::PEXTRB: return "X86ISD::PEXTRB"; 10625 case X86ISD::PEXTRW: return "X86ISD::PEXTRW"; 10626 case X86ISD::INSERTPS: return "X86ISD::INSERTPS"; 10627 case X86ISD::PINSRB: return "X86ISD::PINSRB"; 10628 case X86ISD::PINSRW: return "X86ISD::PINSRW"; 10629 case X86ISD::PSHUFB: return "X86ISD::PSHUFB"; 10630 case X86ISD::ANDNP: return "X86ISD::ANDNP"; 10631 case X86ISD::PSIGNB: return "X86ISD::PSIGNB"; 10632 case X86ISD::PSIGNW: return "X86ISD::PSIGNW"; 10633 case X86ISD::PSIGND: return "X86ISD::PSIGND"; 10634 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB"; 10635 case X86ISD::FMAX: return "X86ISD::FMAX"; 10636 case X86ISD::FMIN: return "X86ISD::FMIN"; 10637 case X86ISD::FRSQRT: return "X86ISD::FRSQRT"; 10638 case X86ISD::FRCP: return "X86ISD::FRCP"; 10639 case X86ISD::TLSADDR: return "X86ISD::TLSADDR"; 10640 case X86ISD::TLSCALL: return "X86ISD::TLSCALL"; 10641 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN"; 10642 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN"; 10643 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m"; 10644 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG"; 10645 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG"; 10646 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG"; 10647 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG"; 10648 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG"; 10649 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG"; 10650 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG"; 10651 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG"; 10652 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL"; 10653 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD"; 10654 case X86ISD::VSHL: return "X86ISD::VSHL"; 10655 case X86ISD::VSRL: return "X86ISD::VSRL"; 10656 case X86ISD::CMPPD: return "X86ISD::CMPPD"; 10657 case X86ISD::CMPPS: return "X86ISD::CMPPS"; 10658 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB"; 10659 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW"; 10660 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD"; 10661 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ"; 10662 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB"; 10663 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW"; 10664 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD"; 10665 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ"; 10666 case X86ISD::ADD: return "X86ISD::ADD"; 10667 case X86ISD::SUB: return "X86ISD::SUB"; 10668 case X86ISD::ADC: return "X86ISD::ADC"; 10669 case X86ISD::SBB: return "X86ISD::SBB"; 10670 case X86ISD::SMUL: return "X86ISD::SMUL"; 10671 case X86ISD::UMUL: return "X86ISD::UMUL"; 10672 case X86ISD::INC: return "X86ISD::INC"; 10673 case X86ISD::DEC: return "X86ISD::DEC"; 10674 case X86ISD::OR: return "X86ISD::OR"; 10675 case X86ISD::XOR: return "X86ISD::XOR"; 10676 case X86ISD::AND: return "X86ISD::AND"; 10677 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM"; 10678 case X86ISD::PTEST: return "X86ISD::PTEST"; 10679 case X86ISD::TESTP: return "X86ISD::TESTP"; 10680 case X86ISD::PALIGN: return "X86ISD::PALIGN"; 10681 case X86ISD::PSHUFD: return "X86ISD::PSHUFD"; 10682 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW"; 10683 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD"; 10684 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW"; 10685 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD"; 10686 case X86ISD::SHUFPS: return "X86ISD::SHUFPS"; 10687 case X86ISD::SHUFPD: return "X86ISD::SHUFPD"; 10688 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS"; 10689 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD"; 10690 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS"; 10691 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD"; 10692 case X86ISD::MOVLPS: return "X86ISD::MOVLPS"; 10693 case X86ISD::MOVLPD: return "X86ISD::MOVLPD"; 10694 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP"; 10695 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP"; 10696 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP"; 10697 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD"; 10698 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD"; 10699 case X86ISD::MOVSD: return "X86ISD::MOVSD"; 10700 case X86ISD::MOVSS: return "X86ISD::MOVSS"; 10701 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS"; 10702 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD"; 10703 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY"; 10704 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS"; 10705 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD"; 10706 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW"; 10707 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD"; 10708 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ"; 10709 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ"; 10710 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW"; 10711 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD"; 10712 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ"; 10713 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ"; 10714 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST"; 10715 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS"; 10716 case X86ISD::VPERMILPSY: return "X86ISD::VPERMILPSY"; 10717 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD"; 10718 case X86ISD::VPERMILPDY: return "X86ISD::VPERMILPDY"; 10719 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128"; 10720 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS"; 10721 case X86ISD::VAARG_64: return "X86ISD::VAARG_64"; 10722 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA"; 10723 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER"; 10724 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA"; 10725 } 10726} 10727 10728// isLegalAddressingMode - Return true if the addressing mode represented 10729// by AM is legal for this target, for a load/store of the specified type. 10730bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 10731 Type *Ty) const { 10732 // X86 supports extremely general addressing modes. 10733 CodeModel::Model M = getTargetMachine().getCodeModel(); 10734 Reloc::Model R = getTargetMachine().getRelocationModel(); 10735 10736 // X86 allows a sign-extended 32-bit immediate field as a displacement. 10737 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL)) 10738 return false; 10739 10740 if (AM.BaseGV) { 10741 unsigned GVFlags = 10742 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine()); 10743 10744 // If a reference to this global requires an extra load, we can't fold it. 10745 if (isGlobalStubReference(GVFlags)) 10746 return false; 10747 10748 // If BaseGV requires a register for the PIC base, we cannot also have a 10749 // BaseReg specified. 10750 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags)) 10751 return false; 10752 10753 // If lower 4G is not available, then we must use rip-relative addressing. 10754 if ((M != CodeModel::Small || R != Reloc::Static) && 10755 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1)) 10756 return false; 10757 } 10758 10759 switch (AM.Scale) { 10760 case 0: 10761 case 1: 10762 case 2: 10763 case 4: 10764 case 8: 10765 // These scales always work. 10766 break; 10767 case 3: 10768 case 5: 10769 case 9: 10770 // These scales are formed with basereg+scalereg. Only accept if there is 10771 // no basereg yet. 10772 if (AM.HasBaseReg) 10773 return false; 10774 break; 10775 default: // Other stuff never works. 10776 return false; 10777 } 10778 10779 return true; 10780} 10781 10782 10783bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 10784 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10785 return false; 10786 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 10787 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 10788 if (NumBits1 <= NumBits2) 10789 return false; 10790 return true; 10791} 10792 10793bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 10794 if (!VT1.isInteger() || !VT2.isInteger()) 10795 return false; 10796 unsigned NumBits1 = VT1.getSizeInBits(); 10797 unsigned NumBits2 = VT2.getSizeInBits(); 10798 if (NumBits1 <= NumBits2) 10799 return false; 10800 return true; 10801} 10802 10803bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 10804 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 10805 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit(); 10806} 10807 10808bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 10809 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 10810 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit(); 10811} 10812 10813bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const { 10814 // i16 instructions are longer (0x66 prefix) and potentially slower. 10815 return !(VT1 == MVT::i32 && VT2 == MVT::i16); 10816} 10817 10818/// isShuffleMaskLegal - Targets can use this to indicate that they only 10819/// support *some* VECTOR_SHUFFLE operations, those with specific masks. 10820/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 10821/// are assumed to be legal. 10822bool 10823X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 10824 EVT VT) const { 10825 // Very little shuffling can be done for 64-bit vectors right now. 10826 if (VT.getSizeInBits() == 64) 10827 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3()); 10828 10829 // FIXME: pshufb, blends, shifts. 10830 return (VT.getVectorNumElements() == 2 || 10831 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 10832 isMOVLMask(M, VT) || 10833 isSHUFPMask(M, VT) || 10834 isPSHUFDMask(M, VT) || 10835 isPSHUFHWMask(M, VT) || 10836 isPSHUFLWMask(M, VT) || 10837 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) || 10838 isUNPCKLMask(M, VT) || 10839 isUNPCKHMask(M, VT) || 10840 isUNPCKL_v_undef_Mask(M, VT) || 10841 isUNPCKH_v_undef_Mask(M, VT)); 10842} 10843 10844bool 10845X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 10846 EVT VT) const { 10847 unsigned NumElts = VT.getVectorNumElements(); 10848 // FIXME: This collection of masks seems suspect. 10849 if (NumElts == 2) 10850 return true; 10851 if (NumElts == 4 && VT.getSizeInBits() == 128) { 10852 return (isMOVLMask(Mask, VT) || 10853 isCommutedMOVLMask(Mask, VT, true) || 10854 isSHUFPMask(Mask, VT) || 10855 isCommutedSHUFPMask(Mask, VT)); 10856 } 10857 return false; 10858} 10859 10860//===----------------------------------------------------------------------===// 10861// X86 Scheduler Hooks 10862//===----------------------------------------------------------------------===// 10863 10864// private utility function 10865MachineBasicBlock * 10866X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr, 10867 MachineBasicBlock *MBB, 10868 unsigned regOpc, 10869 unsigned immOpc, 10870 unsigned LoadOpc, 10871 unsigned CXchgOpc, 10872 unsigned notOpc, 10873 unsigned EAXreg, 10874 TargetRegisterClass *RC, 10875 bool invSrc) const { 10876 // For the atomic bitwise operator, we generate 10877 // thisMBB: 10878 // newMBB: 10879 // ld t1 = [bitinstr.addr] 10880 // op t2 = t1, [bitinstr.val] 10881 // mov EAX = t1 10882 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 10883 // bz newMBB 10884 // fallthrough -->nextMBB 10885 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10886 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 10887 MachineFunction::iterator MBBIter = MBB; 10888 ++MBBIter; 10889 10890 /// First build the CFG 10891 MachineFunction *F = MBB->getParent(); 10892 MachineBasicBlock *thisMBB = MBB; 10893 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 10894 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 10895 F->insert(MBBIter, newMBB); 10896 F->insert(MBBIter, nextMBB); 10897 10898 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 10899 nextMBB->splice(nextMBB->begin(), thisMBB, 10900 llvm::next(MachineBasicBlock::iterator(bInstr)), 10901 thisMBB->end()); 10902 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 10903 10904 // Update thisMBB to fall through to newMBB 10905 thisMBB->addSuccessor(newMBB); 10906 10907 // newMBB jumps to itself and fall through to nextMBB 10908 newMBB->addSuccessor(nextMBB); 10909 newMBB->addSuccessor(newMBB); 10910 10911 // Insert instructions into newMBB based on incoming instruction 10912 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 && 10913 "unexpected number of operands"); 10914 DebugLoc dl = bInstr->getDebugLoc(); 10915 MachineOperand& destOper = bInstr->getOperand(0); 10916 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 10917 int numArgs = bInstr->getNumOperands() - 1; 10918 for (int i=0; i < numArgs; ++i) 10919 argOpers[i] = &bInstr->getOperand(i+1); 10920 10921 // x86 address has 4 operands: base, index, scale, and displacement 10922 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 10923 int valArgIndx = lastAddrIndx + 1; 10924 10925 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 10926 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1); 10927 for (int i=0; i <= lastAddrIndx; ++i) 10928 (*MIB).addOperand(*argOpers[i]); 10929 10930 unsigned tt = F->getRegInfo().createVirtualRegister(RC); 10931 if (invSrc) { 10932 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1); 10933 } 10934 else 10935 tt = t1; 10936 10937 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 10938 assert((argOpers[valArgIndx]->isReg() || 10939 argOpers[valArgIndx]->isImm()) && 10940 "invalid operand"); 10941 if (argOpers[valArgIndx]->isReg()) 10942 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2); 10943 else 10944 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2); 10945 MIB.addReg(tt); 10946 (*MIB).addOperand(*argOpers[valArgIndx]); 10947 10948 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg); 10949 MIB.addReg(t1); 10950 10951 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc)); 10952 for (int i=0; i <= lastAddrIndx; ++i) 10953 (*MIB).addOperand(*argOpers[i]); 10954 MIB.addReg(t2); 10955 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 10956 (*MIB).setMemRefs(bInstr->memoperands_begin(), 10957 bInstr->memoperands_end()); 10958 10959 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 10960 MIB.addReg(EAXreg); 10961 10962 // insert branch 10963 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 10964 10965 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 10966 return nextMBB; 10967} 10968 10969// private utility function: 64 bit atomics on 32 bit host. 10970MachineBasicBlock * 10971X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr, 10972 MachineBasicBlock *MBB, 10973 unsigned regOpcL, 10974 unsigned regOpcH, 10975 unsigned immOpcL, 10976 unsigned immOpcH, 10977 bool invSrc) const { 10978 // For the atomic bitwise operator, we generate 10979 // thisMBB (instructions are in pairs, except cmpxchg8b) 10980 // ld t1,t2 = [bitinstr.addr] 10981 // newMBB: 10982 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4) 10983 // op t5, t6 <- out1, out2, [bitinstr.val] 10984 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val]) 10985 // mov ECX, EBX <- t5, t6 10986 // mov EAX, EDX <- t1, t2 10987 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit] 10988 // mov t3, t4 <- EAX, EDX 10989 // bz newMBB 10990 // result in out1, out2 10991 // fallthrough -->nextMBB 10992 10993 const TargetRegisterClass *RC = X86::GR32RegisterClass; 10994 const unsigned LoadOpc = X86::MOV32rm; 10995 const unsigned NotOpc = X86::NOT32r; 10996 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10997 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 10998 MachineFunction::iterator MBBIter = MBB; 10999 ++MBBIter; 11000 11001 /// First build the CFG 11002 MachineFunction *F = MBB->getParent(); 11003 MachineBasicBlock *thisMBB = MBB; 11004 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11005 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11006 F->insert(MBBIter, newMBB); 11007 F->insert(MBBIter, nextMBB); 11008 11009 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11010 nextMBB->splice(nextMBB->begin(), thisMBB, 11011 llvm::next(MachineBasicBlock::iterator(bInstr)), 11012 thisMBB->end()); 11013 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11014 11015 // Update thisMBB to fall through to newMBB 11016 thisMBB->addSuccessor(newMBB); 11017 11018 // newMBB jumps to itself and fall through to nextMBB 11019 newMBB->addSuccessor(nextMBB); 11020 newMBB->addSuccessor(newMBB); 11021 11022 DebugLoc dl = bInstr->getDebugLoc(); 11023 // Insert instructions into newMBB based on incoming instruction 11024 // There are 8 "real" operands plus 9 implicit def/uses, ignored here. 11025 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 && 11026 "unexpected number of operands"); 11027 MachineOperand& dest1Oper = bInstr->getOperand(0); 11028 MachineOperand& dest2Oper = bInstr->getOperand(1); 11029 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11030 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) { 11031 argOpers[i] = &bInstr->getOperand(i+2); 11032 11033 // We use some of the operands multiple times, so conservatively just 11034 // clear any kill flags that might be present. 11035 if (argOpers[i]->isReg() && argOpers[i]->isUse()) 11036 argOpers[i]->setIsKill(false); 11037 } 11038 11039 // x86 address has 5 operands: base, index, scale, displacement, and segment. 11040 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11041 11042 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 11043 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1); 11044 for (int i=0; i <= lastAddrIndx; ++i) 11045 (*MIB).addOperand(*argOpers[i]); 11046 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 11047 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2); 11048 // add 4 to displacement. 11049 for (int i=0; i <= lastAddrIndx-2; ++i) 11050 (*MIB).addOperand(*argOpers[i]); 11051 MachineOperand newOp3 = *(argOpers[3]); 11052 if (newOp3.isImm()) 11053 newOp3.setImm(newOp3.getImm()+4); 11054 else 11055 newOp3.setOffset(newOp3.getOffset()+4); 11056 (*MIB).addOperand(newOp3); 11057 (*MIB).addOperand(*argOpers[lastAddrIndx]); 11058 11059 // t3/4 are defined later, at the bottom of the loop 11060 unsigned t3 = F->getRegInfo().createVirtualRegister(RC); 11061 unsigned t4 = F->getRegInfo().createVirtualRegister(RC); 11062 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg()) 11063 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB); 11064 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg()) 11065 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB); 11066 11067 // The subsequent operations should be using the destination registers of 11068 //the PHI instructions. 11069 if (invSrc) { 11070 t1 = F->getRegInfo().createVirtualRegister(RC); 11071 t2 = F->getRegInfo().createVirtualRegister(RC); 11072 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg()); 11073 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg()); 11074 } else { 11075 t1 = dest1Oper.getReg(); 11076 t2 = dest2Oper.getReg(); 11077 } 11078 11079 int valArgIndx = lastAddrIndx + 1; 11080 assert((argOpers[valArgIndx]->isReg() || 11081 argOpers[valArgIndx]->isImm()) && 11082 "invalid operand"); 11083 unsigned t5 = F->getRegInfo().createVirtualRegister(RC); 11084 unsigned t6 = F->getRegInfo().createVirtualRegister(RC); 11085 if (argOpers[valArgIndx]->isReg()) 11086 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5); 11087 else 11088 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5); 11089 if (regOpcL != X86::MOV32rr) 11090 MIB.addReg(t1); 11091 (*MIB).addOperand(*argOpers[valArgIndx]); 11092 assert(argOpers[valArgIndx + 1]->isReg() == 11093 argOpers[valArgIndx]->isReg()); 11094 assert(argOpers[valArgIndx + 1]->isImm() == 11095 argOpers[valArgIndx]->isImm()); 11096 if (argOpers[valArgIndx + 1]->isReg()) 11097 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6); 11098 else 11099 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6); 11100 if (regOpcH != X86::MOV32rr) 11101 MIB.addReg(t2); 11102 (*MIB).addOperand(*argOpers[valArgIndx + 1]); 11103 11104 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 11105 MIB.addReg(t1); 11106 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX); 11107 MIB.addReg(t2); 11108 11109 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX); 11110 MIB.addReg(t5); 11111 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX); 11112 MIB.addReg(t6); 11113 11114 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B)); 11115 for (int i=0; i <= lastAddrIndx; ++i) 11116 (*MIB).addOperand(*argOpers[i]); 11117 11118 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11119 (*MIB).setMemRefs(bInstr->memoperands_begin(), 11120 bInstr->memoperands_end()); 11121 11122 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3); 11123 MIB.addReg(X86::EAX); 11124 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4); 11125 MIB.addReg(X86::EDX); 11126 11127 // insert branch 11128 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11129 11130 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 11131 return nextMBB; 11132} 11133 11134// private utility function 11135MachineBasicBlock * 11136X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr, 11137 MachineBasicBlock *MBB, 11138 unsigned cmovOpc) const { 11139 // For the atomic min/max operator, we generate 11140 // thisMBB: 11141 // newMBB: 11142 // ld t1 = [min/max.addr] 11143 // mov t2 = [min/max.val] 11144 // cmp t1, t2 11145 // cmov[cond] t2 = t1 11146 // mov EAX = t1 11147 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 11148 // bz newMBB 11149 // fallthrough -->nextMBB 11150 // 11151 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11152 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11153 MachineFunction::iterator MBBIter = MBB; 11154 ++MBBIter; 11155 11156 /// First build the CFG 11157 MachineFunction *F = MBB->getParent(); 11158 MachineBasicBlock *thisMBB = MBB; 11159 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11160 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11161 F->insert(MBBIter, newMBB); 11162 F->insert(MBBIter, nextMBB); 11163 11164 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11165 nextMBB->splice(nextMBB->begin(), thisMBB, 11166 llvm::next(MachineBasicBlock::iterator(mInstr)), 11167 thisMBB->end()); 11168 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11169 11170 // Update thisMBB to fall through to newMBB 11171 thisMBB->addSuccessor(newMBB); 11172 11173 // newMBB jumps to newMBB and fall through to nextMBB 11174 newMBB->addSuccessor(nextMBB); 11175 newMBB->addSuccessor(newMBB); 11176 11177 DebugLoc dl = mInstr->getDebugLoc(); 11178 // Insert instructions into newMBB based on incoming instruction 11179 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 && 11180 "unexpected number of operands"); 11181 MachineOperand& destOper = mInstr->getOperand(0); 11182 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11183 int numArgs = mInstr->getNumOperands() - 1; 11184 for (int i=0; i < numArgs; ++i) 11185 argOpers[i] = &mInstr->getOperand(i+1); 11186 11187 // x86 address has 4 operands: base, index, scale, and displacement 11188 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11189 int valArgIndx = lastAddrIndx + 1; 11190 11191 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 11192 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1); 11193 for (int i=0; i <= lastAddrIndx; ++i) 11194 (*MIB).addOperand(*argOpers[i]); 11195 11196 // We only support register and immediate values 11197 assert((argOpers[valArgIndx]->isReg() || 11198 argOpers[valArgIndx]->isImm()) && 11199 "invalid operand"); 11200 11201 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 11202 if (argOpers[valArgIndx]->isReg()) 11203 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2); 11204 else 11205 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2); 11206 (*MIB).addOperand(*argOpers[valArgIndx]); 11207 11208 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 11209 MIB.addReg(t1); 11210 11211 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr)); 11212 MIB.addReg(t1); 11213 MIB.addReg(t2); 11214 11215 // Generate movc 11216 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 11217 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3); 11218 MIB.addReg(t2); 11219 MIB.addReg(t1); 11220 11221 // Cmp and exchange if none has modified the memory location 11222 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32)); 11223 for (int i=0; i <= lastAddrIndx; ++i) 11224 (*MIB).addOperand(*argOpers[i]); 11225 MIB.addReg(t3); 11226 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11227 (*MIB).setMemRefs(mInstr->memoperands_begin(), 11228 mInstr->memoperands_end()); 11229 11230 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 11231 MIB.addReg(X86::EAX); 11232 11233 // insert branch 11234 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11235 11236 mInstr->eraseFromParent(); // The pseudo instruction is gone now. 11237 return nextMBB; 11238} 11239 11240// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8 11241// or XMM0_V32I8 in AVX all of this code can be replaced with that 11242// in the .td file. 11243MachineBasicBlock * 11244X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB, 11245 unsigned numArgs, bool memArg) const { 11246 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) && 11247 "Target must have SSE4.2 or AVX features enabled"); 11248 11249 DebugLoc dl = MI->getDebugLoc(); 11250 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11251 unsigned Opc; 11252 if (!Subtarget->hasAVX()) { 11253 if (memArg) 11254 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm; 11255 else 11256 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr; 11257 } else { 11258 if (memArg) 11259 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm; 11260 else 11261 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr; 11262 } 11263 11264 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 11265 for (unsigned i = 0; i < numArgs; ++i) { 11266 MachineOperand &Op = MI->getOperand(i+1); 11267 if (!(Op.isReg() && Op.isImplicit())) 11268 MIB.addOperand(Op); 11269 } 11270 BuildMI(*BB, MI, dl, 11271 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr), 11272 MI->getOperand(0).getReg()) 11273 .addReg(X86::XMM0); 11274 11275 MI->eraseFromParent(); 11276 return BB; 11277} 11278 11279MachineBasicBlock * 11280X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const { 11281 DebugLoc dl = MI->getDebugLoc(); 11282 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11283 11284 // Address into RAX/EAX, other two args into ECX, EDX. 11285 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 11286 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 11287 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg); 11288 for (int i = 0; i < X86::AddrNumOperands; ++i) 11289 MIB.addOperand(MI->getOperand(i)); 11290 11291 unsigned ValOps = X86::AddrNumOperands; 11292 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 11293 .addReg(MI->getOperand(ValOps).getReg()); 11294 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX) 11295 .addReg(MI->getOperand(ValOps+1).getReg()); 11296 11297 // The instruction doesn't actually take any operands though. 11298 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr)); 11299 11300 MI->eraseFromParent(); // The pseudo is gone now. 11301 return BB; 11302} 11303 11304MachineBasicBlock * 11305X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const { 11306 DebugLoc dl = MI->getDebugLoc(); 11307 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11308 11309 // First arg in ECX, the second in EAX. 11310 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 11311 .addReg(MI->getOperand(0).getReg()); 11312 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX) 11313 .addReg(MI->getOperand(1).getReg()); 11314 11315 // The instruction doesn't actually take any operands though. 11316 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr)); 11317 11318 MI->eraseFromParent(); // The pseudo is gone now. 11319 return BB; 11320} 11321 11322MachineBasicBlock * 11323X86TargetLowering::EmitVAARG64WithCustomInserter( 11324 MachineInstr *MI, 11325 MachineBasicBlock *MBB) const { 11326 // Emit va_arg instruction on X86-64. 11327 11328 // Operands to this pseudo-instruction: 11329 // 0 ) Output : destination address (reg) 11330 // 1-5) Input : va_list address (addr, i64mem) 11331 // 6 ) ArgSize : Size (in bytes) of vararg type 11332 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset 11333 // 8 ) Align : Alignment of type 11334 // 9 ) EFLAGS (implicit-def) 11335 11336 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!"); 11337 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands"); 11338 11339 unsigned DestReg = MI->getOperand(0).getReg(); 11340 MachineOperand &Base = MI->getOperand(1); 11341 MachineOperand &Scale = MI->getOperand(2); 11342 MachineOperand &Index = MI->getOperand(3); 11343 MachineOperand &Disp = MI->getOperand(4); 11344 MachineOperand &Segment = MI->getOperand(5); 11345 unsigned ArgSize = MI->getOperand(6).getImm(); 11346 unsigned ArgMode = MI->getOperand(7).getImm(); 11347 unsigned Align = MI->getOperand(8).getImm(); 11348 11349 // Memory Reference 11350 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"); 11351 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 11352 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 11353 11354 // Machine Information 11355 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11356 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 11357 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64); 11358 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32); 11359 DebugLoc DL = MI->getDebugLoc(); 11360 11361 // struct va_list { 11362 // i32 gp_offset 11363 // i32 fp_offset 11364 // i64 overflow_area (address) 11365 // i64 reg_save_area (address) 11366 // } 11367 // sizeof(va_list) = 24 11368 // alignment(va_list) = 8 11369 11370 unsigned TotalNumIntRegs = 6; 11371 unsigned TotalNumXMMRegs = 8; 11372 bool UseGPOffset = (ArgMode == 1); 11373 bool UseFPOffset = (ArgMode == 2); 11374 unsigned MaxOffset = TotalNumIntRegs * 8 + 11375 (UseFPOffset ? TotalNumXMMRegs * 16 : 0); 11376 11377 /* Align ArgSize to a multiple of 8 */ 11378 unsigned ArgSizeA8 = (ArgSize + 7) & ~7; 11379 bool NeedsAlign = (Align > 8); 11380 11381 MachineBasicBlock *thisMBB = MBB; 11382 MachineBasicBlock *overflowMBB; 11383 MachineBasicBlock *offsetMBB; 11384 MachineBasicBlock *endMBB; 11385 11386 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB 11387 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB 11388 unsigned OffsetReg = 0; 11389 11390 if (!UseGPOffset && !UseFPOffset) { 11391 // If we only pull from the overflow region, we don't create a branch. 11392 // We don't need to alter control flow. 11393 OffsetDestReg = 0; // unused 11394 OverflowDestReg = DestReg; 11395 11396 offsetMBB = NULL; 11397 overflowMBB = thisMBB; 11398 endMBB = thisMBB; 11399 } else { 11400 // First emit code to check if gp_offset (or fp_offset) is below the bound. 11401 // If so, pull the argument from reg_save_area. (branch to offsetMBB) 11402 // If not, pull from overflow_area. (branch to overflowMBB) 11403 // 11404 // thisMBB 11405 // | . 11406 // | . 11407 // offsetMBB overflowMBB 11408 // | . 11409 // | . 11410 // endMBB 11411 11412 // Registers for the PHI in endMBB 11413 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass); 11414 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass); 11415 11416 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11417 MachineFunction *MF = MBB->getParent(); 11418 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11419 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11420 endMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11421 11422 MachineFunction::iterator MBBIter = MBB; 11423 ++MBBIter; 11424 11425 // Insert the new basic blocks 11426 MF->insert(MBBIter, offsetMBB); 11427 MF->insert(MBBIter, overflowMBB); 11428 MF->insert(MBBIter, endMBB); 11429 11430 // Transfer the remainder of MBB and its successor edges to endMBB. 11431 endMBB->splice(endMBB->begin(), thisMBB, 11432 llvm::next(MachineBasicBlock::iterator(MI)), 11433 thisMBB->end()); 11434 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11435 11436 // Make offsetMBB and overflowMBB successors of thisMBB 11437 thisMBB->addSuccessor(offsetMBB); 11438 thisMBB->addSuccessor(overflowMBB); 11439 11440 // endMBB is a successor of both offsetMBB and overflowMBB 11441 offsetMBB->addSuccessor(endMBB); 11442 overflowMBB->addSuccessor(endMBB); 11443 11444 // Load the offset value into a register 11445 OffsetReg = MRI.createVirtualRegister(OffsetRegClass); 11446 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg) 11447 .addOperand(Base) 11448 .addOperand(Scale) 11449 .addOperand(Index) 11450 .addDisp(Disp, UseFPOffset ? 4 : 0) 11451 .addOperand(Segment) 11452 .setMemRefs(MMOBegin, MMOEnd); 11453 11454 // Check if there is enough room left to pull this argument. 11455 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri)) 11456 .addReg(OffsetReg) 11457 .addImm(MaxOffset + 8 - ArgSizeA8); 11458 11459 // Branch to "overflowMBB" if offset >= max 11460 // Fall through to "offsetMBB" otherwise 11461 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE))) 11462 .addMBB(overflowMBB); 11463 } 11464 11465 // In offsetMBB, emit code to use the reg_save_area. 11466 if (offsetMBB) { 11467 assert(OffsetReg != 0); 11468 11469 // Read the reg_save_area address. 11470 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass); 11471 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg) 11472 .addOperand(Base) 11473 .addOperand(Scale) 11474 .addOperand(Index) 11475 .addDisp(Disp, 16) 11476 .addOperand(Segment) 11477 .setMemRefs(MMOBegin, MMOEnd); 11478 11479 // Zero-extend the offset 11480 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass); 11481 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64) 11482 .addImm(0) 11483 .addReg(OffsetReg) 11484 .addImm(X86::sub_32bit); 11485 11486 // Add the offset to the reg_save_area to get the final address. 11487 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg) 11488 .addReg(OffsetReg64) 11489 .addReg(RegSaveReg); 11490 11491 // Compute the offset for the next argument 11492 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass); 11493 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg) 11494 .addReg(OffsetReg) 11495 .addImm(UseFPOffset ? 16 : 8); 11496 11497 // Store it back into the va_list. 11498 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr)) 11499 .addOperand(Base) 11500 .addOperand(Scale) 11501 .addOperand(Index) 11502 .addDisp(Disp, UseFPOffset ? 4 : 0) 11503 .addOperand(Segment) 11504 .addReg(NextOffsetReg) 11505 .setMemRefs(MMOBegin, MMOEnd); 11506 11507 // Jump to endMBB 11508 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4)) 11509 .addMBB(endMBB); 11510 } 11511 11512 // 11513 // Emit code to use overflow area 11514 // 11515 11516 // Load the overflow_area address into a register. 11517 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass); 11518 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg) 11519 .addOperand(Base) 11520 .addOperand(Scale) 11521 .addOperand(Index) 11522 .addDisp(Disp, 8) 11523 .addOperand(Segment) 11524 .setMemRefs(MMOBegin, MMOEnd); 11525 11526 // If we need to align it, do so. Otherwise, just copy the address 11527 // to OverflowDestReg. 11528 if (NeedsAlign) { 11529 // Align the overflow address 11530 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2"); 11531 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass); 11532 11533 // aligned_addr = (addr + (align-1)) & ~(align-1) 11534 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg) 11535 .addReg(OverflowAddrReg) 11536 .addImm(Align-1); 11537 11538 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg) 11539 .addReg(TmpReg) 11540 .addImm(~(uint64_t)(Align-1)); 11541 } else { 11542 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg) 11543 .addReg(OverflowAddrReg); 11544 } 11545 11546 // Compute the next overflow address after this argument. 11547 // (the overflow address should be kept 8-byte aligned) 11548 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass); 11549 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg) 11550 .addReg(OverflowDestReg) 11551 .addImm(ArgSizeA8); 11552 11553 // Store the new overflow address. 11554 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr)) 11555 .addOperand(Base) 11556 .addOperand(Scale) 11557 .addOperand(Index) 11558 .addDisp(Disp, 8) 11559 .addOperand(Segment) 11560 .addReg(NextAddrReg) 11561 .setMemRefs(MMOBegin, MMOEnd); 11562 11563 // If we branched, emit the PHI to the front of endMBB. 11564 if (offsetMBB) { 11565 BuildMI(*endMBB, endMBB->begin(), DL, 11566 TII->get(X86::PHI), DestReg) 11567 .addReg(OffsetDestReg).addMBB(offsetMBB) 11568 .addReg(OverflowDestReg).addMBB(overflowMBB); 11569 } 11570 11571 // Erase the pseudo instruction 11572 MI->eraseFromParent(); 11573 11574 return endMBB; 11575} 11576 11577MachineBasicBlock * 11578X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter( 11579 MachineInstr *MI, 11580 MachineBasicBlock *MBB) const { 11581 // Emit code to save XMM registers to the stack. The ABI says that the 11582 // number of registers to save is given in %al, so it's theoretically 11583 // possible to do an indirect jump trick to avoid saving all of them, 11584 // however this code takes a simpler approach and just executes all 11585 // of the stores if %al is non-zero. It's less code, and it's probably 11586 // easier on the hardware branch predictor, and stores aren't all that 11587 // expensive anyway. 11588 11589 // Create the new basic blocks. One block contains all the XMM stores, 11590 // and one block is the final destination regardless of whether any 11591 // stores were performed. 11592 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11593 MachineFunction *F = MBB->getParent(); 11594 MachineFunction::iterator MBBIter = MBB; 11595 ++MBBIter; 11596 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB); 11597 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB); 11598 F->insert(MBBIter, XMMSaveMBB); 11599 F->insert(MBBIter, EndMBB); 11600 11601 // Transfer the remainder of MBB and its successor edges to EndMBB. 11602 EndMBB->splice(EndMBB->begin(), MBB, 11603 llvm::next(MachineBasicBlock::iterator(MI)), 11604 MBB->end()); 11605 EndMBB->transferSuccessorsAndUpdatePHIs(MBB); 11606 11607 // The original block will now fall through to the XMM save block. 11608 MBB->addSuccessor(XMMSaveMBB); 11609 // The XMMSaveMBB will fall through to the end block. 11610 XMMSaveMBB->addSuccessor(EndMBB); 11611 11612 // Now add the instructions. 11613 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11614 DebugLoc DL = MI->getDebugLoc(); 11615 11616 unsigned CountReg = MI->getOperand(0).getReg(); 11617 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm(); 11618 int64_t VarArgsFPOffset = MI->getOperand(2).getImm(); 11619 11620 if (!Subtarget->isTargetWin64()) { 11621 // If %al is 0, branch around the XMM save block. 11622 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg); 11623 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB); 11624 MBB->addSuccessor(EndMBB); 11625 } 11626 11627 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr; 11628 // In the XMM save block, save all the XMM argument registers. 11629 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) { 11630 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset; 11631 MachineMemOperand *MMO = 11632 F->getMachineMemOperand( 11633 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset), 11634 MachineMemOperand::MOStore, 11635 /*Size=*/16, /*Align=*/16); 11636 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc)) 11637 .addFrameIndex(RegSaveFrameIndex) 11638 .addImm(/*Scale=*/1) 11639 .addReg(/*IndexReg=*/0) 11640 .addImm(/*Disp=*/Offset) 11641 .addReg(/*Segment=*/0) 11642 .addReg(MI->getOperand(i).getReg()) 11643 .addMemOperand(MMO); 11644 } 11645 11646 MI->eraseFromParent(); // The pseudo instruction is gone now. 11647 11648 return EndMBB; 11649} 11650 11651MachineBasicBlock * 11652X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, 11653 MachineBasicBlock *BB) const { 11654 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11655 DebugLoc DL = MI->getDebugLoc(); 11656 11657 // To "insert" a SELECT_CC instruction, we actually have to insert the 11658 // diamond control-flow pattern. The incoming instruction knows the 11659 // destination vreg to set, the condition code register to branch on, the 11660 // true/false values to select between, and a branch opcode to use. 11661 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11662 MachineFunction::iterator It = BB; 11663 ++It; 11664 11665 // thisMBB: 11666 // ... 11667 // TrueVal = ... 11668 // cmpTY ccX, r1, r2 11669 // bCC copy1MBB 11670 // fallthrough --> copy0MBB 11671 MachineBasicBlock *thisMBB = BB; 11672 MachineFunction *F = BB->getParent(); 11673 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11674 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11675 F->insert(It, copy0MBB); 11676 F->insert(It, sinkMBB); 11677 11678 // If the EFLAGS register isn't dead in the terminator, then claim that it's 11679 // live into the sink and copy blocks. 11680 if (!MI->killsRegister(X86::EFLAGS)) { 11681 copy0MBB->addLiveIn(X86::EFLAGS); 11682 sinkMBB->addLiveIn(X86::EFLAGS); 11683 } 11684 11685 // Transfer the remainder of BB and its successor edges to sinkMBB. 11686 sinkMBB->splice(sinkMBB->begin(), BB, 11687 llvm::next(MachineBasicBlock::iterator(MI)), 11688 BB->end()); 11689 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11690 11691 // Add the true and fallthrough blocks as its successors. 11692 BB->addSuccessor(copy0MBB); 11693 BB->addSuccessor(sinkMBB); 11694 11695 // Create the conditional branch instruction. 11696 unsigned Opc = 11697 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm()); 11698 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB); 11699 11700 // copy0MBB: 11701 // %FalseValue = ... 11702 // # fallthrough to sinkMBB 11703 copy0MBB->addSuccessor(sinkMBB); 11704 11705 // sinkMBB: 11706 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11707 // ... 11708 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11709 TII->get(X86::PHI), MI->getOperand(0).getReg()) 11710 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 11711 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 11712 11713 MI->eraseFromParent(); // The pseudo instruction is gone now. 11714 return sinkMBB; 11715} 11716 11717MachineBasicBlock * 11718X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB, 11719 bool Is64Bit) const { 11720 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11721 DebugLoc DL = MI->getDebugLoc(); 11722 MachineFunction *MF = BB->getParent(); 11723 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11724 11725 assert(EnableSegmentedStacks); 11726 11727 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS; 11728 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30; 11729 11730 // BB: 11731 // ... [Till the alloca] 11732 // If stacklet is not large enough, jump to mallocMBB 11733 // 11734 // bumpMBB: 11735 // Allocate by subtracting from RSP 11736 // Jump to continueMBB 11737 // 11738 // mallocMBB: 11739 // Allocate by call to runtime 11740 // 11741 // continueMBB: 11742 // ... 11743 // [rest of original BB] 11744 // 11745 11746 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11747 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11748 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11749 11750 MachineRegisterInfo &MRI = MF->getRegInfo(); 11751 const TargetRegisterClass *AddrRegClass = 11752 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32); 11753 11754 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass), 11755 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass), 11756 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass), 11757 sizeVReg = MI->getOperand(1).getReg(), 11758 physSPReg = Is64Bit ? X86::RSP : X86::ESP; 11759 11760 MachineFunction::iterator MBBIter = BB; 11761 ++MBBIter; 11762 11763 MF->insert(MBBIter, bumpMBB); 11764 MF->insert(MBBIter, mallocMBB); 11765 MF->insert(MBBIter, continueMBB); 11766 11767 continueMBB->splice(continueMBB->begin(), BB, llvm::next 11768 (MachineBasicBlock::iterator(MI)), BB->end()); 11769 continueMBB->transferSuccessorsAndUpdatePHIs(BB); 11770 11771 // Add code to the main basic block to check if the stack limit has been hit, 11772 // and if so, jump to mallocMBB otherwise to bumpMBB. 11773 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg); 11774 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg) 11775 .addReg(tmpSPVReg).addReg(sizeVReg); 11776 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr)) 11777 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg) 11778 .addReg(tmpSPVReg); 11779 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB); 11780 11781 // bumpMBB simply decreases the stack pointer, since we know the current 11782 // stacklet has enough space. 11783 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg) 11784 .addReg(tmpSPVReg); 11785 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg) 11786 .addReg(tmpSPVReg); 11787 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 11788 11789 // Calls into a routine in libgcc to allocate more space from the heap. 11790 if (Is64Bit) { 11791 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI) 11792 .addReg(sizeVReg); 11793 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32)) 11794 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI); 11795 } else { 11796 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg) 11797 .addImm(12); 11798 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg); 11799 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32)) 11800 .addExternalSymbol("__morestack_allocate_stack_space"); 11801 } 11802 11803 if (!Is64Bit) 11804 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg) 11805 .addImm(16); 11806 11807 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg) 11808 .addReg(Is64Bit ? X86::RAX : X86::EAX); 11809 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 11810 11811 // Set up the CFG correctly. 11812 BB->addSuccessor(bumpMBB); 11813 BB->addSuccessor(mallocMBB); 11814 mallocMBB->addSuccessor(continueMBB); 11815 bumpMBB->addSuccessor(continueMBB); 11816 11817 // Take care of the PHI nodes. 11818 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI), 11819 MI->getOperand(0).getReg()) 11820 .addReg(mallocPtrVReg).addMBB(mallocMBB) 11821 .addReg(bumpSPPtrVReg).addMBB(bumpMBB); 11822 11823 // Delete the original pseudo instruction. 11824 MI->eraseFromParent(); 11825 11826 // And we're done. 11827 return continueMBB; 11828} 11829 11830MachineBasicBlock * 11831X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI, 11832 MachineBasicBlock *BB) const { 11833 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11834 DebugLoc DL = MI->getDebugLoc(); 11835 11836 assert(!Subtarget->isTargetEnvMacho()); 11837 11838 // The lowering is pretty easy: we're just emitting the call to _alloca. The 11839 // non-trivial part is impdef of ESP. 11840 11841 if (Subtarget->isTargetWin64()) { 11842 if (Subtarget->isTargetCygMing()) { 11843 // ___chkstk(Mingw64): 11844 // Clobbers R10, R11, RAX and EFLAGS. 11845 // Updates RSP. 11846 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 11847 .addExternalSymbol("___chkstk") 11848 .addReg(X86::RAX, RegState::Implicit) 11849 .addReg(X86::RSP, RegState::Implicit) 11850 .addReg(X86::RAX, RegState::Define | RegState::Implicit) 11851 .addReg(X86::RSP, RegState::Define | RegState::Implicit) 11852 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 11853 } else { 11854 // __chkstk(MSVCRT): does not update stack pointer. 11855 // Clobbers R10, R11 and EFLAGS. 11856 // FIXME: RAX(allocated size) might be reused and not killed. 11857 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 11858 .addExternalSymbol("__chkstk") 11859 .addReg(X86::RAX, RegState::Implicit) 11860 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 11861 // RAX has the offset to subtracted from RSP. 11862 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP) 11863 .addReg(X86::RSP) 11864 .addReg(X86::RAX); 11865 } 11866 } else { 11867 const char *StackProbeSymbol = 11868 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca"; 11869 11870 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32)) 11871 .addExternalSymbol(StackProbeSymbol) 11872 .addReg(X86::EAX, RegState::Implicit) 11873 .addReg(X86::ESP, RegState::Implicit) 11874 .addReg(X86::EAX, RegState::Define | RegState::Implicit) 11875 .addReg(X86::ESP, RegState::Define | RegState::Implicit) 11876 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 11877 } 11878 11879 MI->eraseFromParent(); // The pseudo instruction is gone now. 11880 return BB; 11881} 11882 11883MachineBasicBlock * 11884X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI, 11885 MachineBasicBlock *BB) const { 11886 // This is pretty easy. We're taking the value that we received from 11887 // our load from the relocation, sticking it in either RDI (x86-64) 11888 // or EAX and doing an indirect call. The return value will then 11889 // be in the normal return register. 11890 const X86InstrInfo *TII 11891 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo()); 11892 DebugLoc DL = MI->getDebugLoc(); 11893 MachineFunction *F = BB->getParent(); 11894 11895 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?"); 11896 assert(MI->getOperand(3).isGlobal() && "This should be a global"); 11897 11898 if (Subtarget->is64Bit()) { 11899 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 11900 TII->get(X86::MOV64rm), X86::RDI) 11901 .addReg(X86::RIP) 11902 .addImm(0).addReg(0) 11903 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 11904 MI->getOperand(3).getTargetFlags()) 11905 .addReg(0); 11906 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m)); 11907 addDirectMem(MIB, X86::RDI); 11908 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) { 11909 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 11910 TII->get(X86::MOV32rm), X86::EAX) 11911 .addReg(0) 11912 .addImm(0).addReg(0) 11913 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 11914 MI->getOperand(3).getTargetFlags()) 11915 .addReg(0); 11916 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 11917 addDirectMem(MIB, X86::EAX); 11918 } else { 11919 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 11920 TII->get(X86::MOV32rm), X86::EAX) 11921 .addReg(TII->getGlobalBaseReg(F)) 11922 .addImm(0).addReg(0) 11923 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 11924 MI->getOperand(3).getTargetFlags()) 11925 .addReg(0); 11926 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 11927 addDirectMem(MIB, X86::EAX); 11928 } 11929 11930 MI->eraseFromParent(); // The pseudo instruction is gone now. 11931 return BB; 11932} 11933 11934MachineBasicBlock * 11935X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 11936 MachineBasicBlock *BB) const { 11937 switch (MI->getOpcode()) { 11938 default: assert(false && "Unexpected instr type to insert"); 11939 case X86::TAILJMPd64: 11940 case X86::TAILJMPr64: 11941 case X86::TAILJMPm64: 11942 assert(!"TAILJMP64 would not be touched here."); 11943 case X86::TCRETURNdi64: 11944 case X86::TCRETURNri64: 11945 case X86::TCRETURNmi64: 11946 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset. 11947 // On AMD64, additional defs should be added before register allocation. 11948 if (!Subtarget->isTargetWin64()) { 11949 MI->addRegisterDefined(X86::RSI); 11950 MI->addRegisterDefined(X86::RDI); 11951 MI->addRegisterDefined(X86::XMM6); 11952 MI->addRegisterDefined(X86::XMM7); 11953 MI->addRegisterDefined(X86::XMM8); 11954 MI->addRegisterDefined(X86::XMM9); 11955 MI->addRegisterDefined(X86::XMM10); 11956 MI->addRegisterDefined(X86::XMM11); 11957 MI->addRegisterDefined(X86::XMM12); 11958 MI->addRegisterDefined(X86::XMM13); 11959 MI->addRegisterDefined(X86::XMM14); 11960 MI->addRegisterDefined(X86::XMM15); 11961 } 11962 return BB; 11963 case X86::WIN_ALLOCA: 11964 return EmitLoweredWinAlloca(MI, BB); 11965 case X86::SEG_ALLOCA_32: 11966 return EmitLoweredSegAlloca(MI, BB, false); 11967 case X86::SEG_ALLOCA_64: 11968 return EmitLoweredSegAlloca(MI, BB, true); 11969 case X86::TLSCall_32: 11970 case X86::TLSCall_64: 11971 return EmitLoweredTLSCall(MI, BB); 11972 case X86::CMOV_GR8: 11973 case X86::CMOV_FR32: 11974 case X86::CMOV_FR64: 11975 case X86::CMOV_V4F32: 11976 case X86::CMOV_V2F64: 11977 case X86::CMOV_V2I64: 11978 case X86::CMOV_V8F32: 11979 case X86::CMOV_V4F64: 11980 case X86::CMOV_V4I64: 11981 case X86::CMOV_GR16: 11982 case X86::CMOV_GR32: 11983 case X86::CMOV_RFP32: 11984 case X86::CMOV_RFP64: 11985 case X86::CMOV_RFP80: 11986 return EmitLoweredSelect(MI, BB); 11987 11988 case X86::FP32_TO_INT16_IN_MEM: 11989 case X86::FP32_TO_INT32_IN_MEM: 11990 case X86::FP32_TO_INT64_IN_MEM: 11991 case X86::FP64_TO_INT16_IN_MEM: 11992 case X86::FP64_TO_INT32_IN_MEM: 11993 case X86::FP64_TO_INT64_IN_MEM: 11994 case X86::FP80_TO_INT16_IN_MEM: 11995 case X86::FP80_TO_INT32_IN_MEM: 11996 case X86::FP80_TO_INT64_IN_MEM: { 11997 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11998 DebugLoc DL = MI->getDebugLoc(); 11999 12000 // Change the floating point control register to use "round towards zero" 12001 // mode when truncating to an integer value. 12002 MachineFunction *F = BB->getParent(); 12003 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false); 12004 addFrameReference(BuildMI(*BB, MI, DL, 12005 TII->get(X86::FNSTCW16m)), CWFrameIdx); 12006 12007 // Load the old value of the high byte of the control word... 12008 unsigned OldCW = 12009 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass); 12010 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW), 12011 CWFrameIdx); 12012 12013 // Set the high part to be round to zero... 12014 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx) 12015 .addImm(0xC7F); 12016 12017 // Reload the modified control word now... 12018 addFrameReference(BuildMI(*BB, MI, DL, 12019 TII->get(X86::FLDCW16m)), CWFrameIdx); 12020 12021 // Restore the memory image of control word to original value 12022 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx) 12023 .addReg(OldCW); 12024 12025 // Get the X86 opcode to use. 12026 unsigned Opc; 12027 switch (MI->getOpcode()) { 12028 default: llvm_unreachable("illegal opcode!"); 12029 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break; 12030 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break; 12031 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break; 12032 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break; 12033 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break; 12034 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break; 12035 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break; 12036 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break; 12037 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break; 12038 } 12039 12040 X86AddressMode AM; 12041 MachineOperand &Op = MI->getOperand(0); 12042 if (Op.isReg()) { 12043 AM.BaseType = X86AddressMode::RegBase; 12044 AM.Base.Reg = Op.getReg(); 12045 } else { 12046 AM.BaseType = X86AddressMode::FrameIndexBase; 12047 AM.Base.FrameIndex = Op.getIndex(); 12048 } 12049 Op = MI->getOperand(1); 12050 if (Op.isImm()) 12051 AM.Scale = Op.getImm(); 12052 Op = MI->getOperand(2); 12053 if (Op.isImm()) 12054 AM.IndexReg = Op.getImm(); 12055 Op = MI->getOperand(3); 12056 if (Op.isGlobal()) { 12057 AM.GV = Op.getGlobal(); 12058 } else { 12059 AM.Disp = Op.getImm(); 12060 } 12061 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM) 12062 .addReg(MI->getOperand(X86::AddrNumOperands).getReg()); 12063 12064 // Reload the original control word now. 12065 addFrameReference(BuildMI(*BB, MI, DL, 12066 TII->get(X86::FLDCW16m)), CWFrameIdx); 12067 12068 MI->eraseFromParent(); // The pseudo instruction is gone now. 12069 return BB; 12070 } 12071 // String/text processing lowering. 12072 case X86::PCMPISTRM128REG: 12073 case X86::VPCMPISTRM128REG: 12074 return EmitPCMP(MI, BB, 3, false /* in-mem */); 12075 case X86::PCMPISTRM128MEM: 12076 case X86::VPCMPISTRM128MEM: 12077 return EmitPCMP(MI, BB, 3, true /* in-mem */); 12078 case X86::PCMPESTRM128REG: 12079 case X86::VPCMPESTRM128REG: 12080 return EmitPCMP(MI, BB, 5, false /* in mem */); 12081 case X86::PCMPESTRM128MEM: 12082 case X86::VPCMPESTRM128MEM: 12083 return EmitPCMP(MI, BB, 5, true /* in mem */); 12084 12085 // Thread synchronization. 12086 case X86::MONITOR: 12087 return EmitMonitor(MI, BB); 12088 case X86::MWAIT: 12089 return EmitMwait(MI, BB); 12090 12091 // Atomic Lowering. 12092 case X86::ATOMAND32: 12093 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 12094 X86::AND32ri, X86::MOV32rm, 12095 X86::LCMPXCHG32, 12096 X86::NOT32r, X86::EAX, 12097 X86::GR32RegisterClass); 12098 case X86::ATOMOR32: 12099 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 12100 X86::OR32ri, X86::MOV32rm, 12101 X86::LCMPXCHG32, 12102 X86::NOT32r, X86::EAX, 12103 X86::GR32RegisterClass); 12104 case X86::ATOMXOR32: 12105 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr, 12106 X86::XOR32ri, X86::MOV32rm, 12107 X86::LCMPXCHG32, 12108 X86::NOT32r, X86::EAX, 12109 X86::GR32RegisterClass); 12110 case X86::ATOMNAND32: 12111 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 12112 X86::AND32ri, X86::MOV32rm, 12113 X86::LCMPXCHG32, 12114 X86::NOT32r, X86::EAX, 12115 X86::GR32RegisterClass, true); 12116 case X86::ATOMMIN32: 12117 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr); 12118 case X86::ATOMMAX32: 12119 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr); 12120 case X86::ATOMUMIN32: 12121 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr); 12122 case X86::ATOMUMAX32: 12123 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr); 12124 12125 case X86::ATOMAND16: 12126 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 12127 X86::AND16ri, X86::MOV16rm, 12128 X86::LCMPXCHG16, 12129 X86::NOT16r, X86::AX, 12130 X86::GR16RegisterClass); 12131 case X86::ATOMOR16: 12132 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 12133 X86::OR16ri, X86::MOV16rm, 12134 X86::LCMPXCHG16, 12135 X86::NOT16r, X86::AX, 12136 X86::GR16RegisterClass); 12137 case X86::ATOMXOR16: 12138 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr, 12139 X86::XOR16ri, X86::MOV16rm, 12140 X86::LCMPXCHG16, 12141 X86::NOT16r, X86::AX, 12142 X86::GR16RegisterClass); 12143 case X86::ATOMNAND16: 12144 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 12145 X86::AND16ri, X86::MOV16rm, 12146 X86::LCMPXCHG16, 12147 X86::NOT16r, X86::AX, 12148 X86::GR16RegisterClass, true); 12149 case X86::ATOMMIN16: 12150 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr); 12151 case X86::ATOMMAX16: 12152 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr); 12153 case X86::ATOMUMIN16: 12154 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr); 12155 case X86::ATOMUMAX16: 12156 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr); 12157 12158 case X86::ATOMAND8: 12159 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 12160 X86::AND8ri, X86::MOV8rm, 12161 X86::LCMPXCHG8, 12162 X86::NOT8r, X86::AL, 12163 X86::GR8RegisterClass); 12164 case X86::ATOMOR8: 12165 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 12166 X86::OR8ri, X86::MOV8rm, 12167 X86::LCMPXCHG8, 12168 X86::NOT8r, X86::AL, 12169 X86::GR8RegisterClass); 12170 case X86::ATOMXOR8: 12171 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr, 12172 X86::XOR8ri, X86::MOV8rm, 12173 X86::LCMPXCHG8, 12174 X86::NOT8r, X86::AL, 12175 X86::GR8RegisterClass); 12176 case X86::ATOMNAND8: 12177 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 12178 X86::AND8ri, X86::MOV8rm, 12179 X86::LCMPXCHG8, 12180 X86::NOT8r, X86::AL, 12181 X86::GR8RegisterClass, true); 12182 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way. 12183 // This group is for 64-bit host. 12184 case X86::ATOMAND64: 12185 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 12186 X86::AND64ri32, X86::MOV64rm, 12187 X86::LCMPXCHG64, 12188 X86::NOT64r, X86::RAX, 12189 X86::GR64RegisterClass); 12190 case X86::ATOMOR64: 12191 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 12192 X86::OR64ri32, X86::MOV64rm, 12193 X86::LCMPXCHG64, 12194 X86::NOT64r, X86::RAX, 12195 X86::GR64RegisterClass); 12196 case X86::ATOMXOR64: 12197 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr, 12198 X86::XOR64ri32, X86::MOV64rm, 12199 X86::LCMPXCHG64, 12200 X86::NOT64r, X86::RAX, 12201 X86::GR64RegisterClass); 12202 case X86::ATOMNAND64: 12203 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 12204 X86::AND64ri32, X86::MOV64rm, 12205 X86::LCMPXCHG64, 12206 X86::NOT64r, X86::RAX, 12207 X86::GR64RegisterClass, true); 12208 case X86::ATOMMIN64: 12209 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr); 12210 case X86::ATOMMAX64: 12211 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr); 12212 case X86::ATOMUMIN64: 12213 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr); 12214 case X86::ATOMUMAX64: 12215 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr); 12216 12217 // This group does 64-bit operations on a 32-bit host. 12218 case X86::ATOMAND6432: 12219 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12220 X86::AND32rr, X86::AND32rr, 12221 X86::AND32ri, X86::AND32ri, 12222 false); 12223 case X86::ATOMOR6432: 12224 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12225 X86::OR32rr, X86::OR32rr, 12226 X86::OR32ri, X86::OR32ri, 12227 false); 12228 case X86::ATOMXOR6432: 12229 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12230 X86::XOR32rr, X86::XOR32rr, 12231 X86::XOR32ri, X86::XOR32ri, 12232 false); 12233 case X86::ATOMNAND6432: 12234 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12235 X86::AND32rr, X86::AND32rr, 12236 X86::AND32ri, X86::AND32ri, 12237 true); 12238 case X86::ATOMADD6432: 12239 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12240 X86::ADD32rr, X86::ADC32rr, 12241 X86::ADD32ri, X86::ADC32ri, 12242 false); 12243 case X86::ATOMSUB6432: 12244 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12245 X86::SUB32rr, X86::SBB32rr, 12246 X86::SUB32ri, X86::SBB32ri, 12247 false); 12248 case X86::ATOMSWAP6432: 12249 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12250 X86::MOV32rr, X86::MOV32rr, 12251 X86::MOV32ri, X86::MOV32ri, 12252 false); 12253 case X86::VASTART_SAVE_XMM_REGS: 12254 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB); 12255 12256 case X86::VAARG_64: 12257 return EmitVAARG64WithCustomInserter(MI, BB); 12258 } 12259} 12260 12261//===----------------------------------------------------------------------===// 12262// X86 Optimization Hooks 12263//===----------------------------------------------------------------------===// 12264 12265void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 12266 const APInt &Mask, 12267 APInt &KnownZero, 12268 APInt &KnownOne, 12269 const SelectionDAG &DAG, 12270 unsigned Depth) const { 12271 unsigned Opc = Op.getOpcode(); 12272 assert((Opc >= ISD::BUILTIN_OP_END || 12273 Opc == ISD::INTRINSIC_WO_CHAIN || 12274 Opc == ISD::INTRINSIC_W_CHAIN || 12275 Opc == ISD::INTRINSIC_VOID) && 12276 "Should use MaskedValueIsZero if you don't know whether Op" 12277 " is a target node!"); 12278 12279 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything. 12280 switch (Opc) { 12281 default: break; 12282 case X86ISD::ADD: 12283 case X86ISD::SUB: 12284 case X86ISD::ADC: 12285 case X86ISD::SBB: 12286 case X86ISD::SMUL: 12287 case X86ISD::UMUL: 12288 case X86ISD::INC: 12289 case X86ISD::DEC: 12290 case X86ISD::OR: 12291 case X86ISD::XOR: 12292 case X86ISD::AND: 12293 // These nodes' second result is a boolean. 12294 if (Op.getResNo() == 0) 12295 break; 12296 // Fallthrough 12297 case X86ISD::SETCC: 12298 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(), 12299 Mask.getBitWidth() - 1); 12300 break; 12301 } 12302} 12303 12304unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 12305 unsigned Depth) const { 12306 // SETCC_CARRY sets the dest to ~0 for true or 0 for false. 12307 if (Op.getOpcode() == X86ISD::SETCC_CARRY) 12308 return Op.getValueType().getScalarType().getSizeInBits(); 12309 12310 // Fallback case. 12311 return 1; 12312} 12313 12314/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 12315/// node is a GlobalAddress + offset. 12316bool X86TargetLowering::isGAPlusOffset(SDNode *N, 12317 const GlobalValue* &GA, 12318 int64_t &Offset) const { 12319 if (N->getOpcode() == X86ISD::Wrapper) { 12320 if (isa<GlobalAddressSDNode>(N->getOperand(0))) { 12321 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal(); 12322 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset(); 12323 return true; 12324 } 12325 } 12326 return TargetLowering::isGAPlusOffset(N, GA, Offset); 12327} 12328 12329/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the 12330/// same as extracting the high 128-bit part of 256-bit vector and then 12331/// inserting the result into the low part of a new 256-bit vector 12332static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) { 12333 EVT VT = SVOp->getValueType(0); 12334 int NumElems = VT.getVectorNumElements(); 12335 12336 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 12337 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j) 12338 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 12339 SVOp->getMaskElt(j) >= 0) 12340 return false; 12341 12342 return true; 12343} 12344 12345/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the 12346/// same as extracting the low 128-bit part of 256-bit vector and then 12347/// inserting the result into the high part of a new 256-bit vector 12348static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) { 12349 EVT VT = SVOp->getValueType(0); 12350 int NumElems = VT.getVectorNumElements(); 12351 12352 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 12353 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j) 12354 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 12355 SVOp->getMaskElt(j) >= 0) 12356 return false; 12357 12358 return true; 12359} 12360 12361/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors. 12362static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG, 12363 TargetLowering::DAGCombinerInfo &DCI) { 12364 DebugLoc dl = N->getDebugLoc(); 12365 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 12366 SDValue V1 = SVOp->getOperand(0); 12367 SDValue V2 = SVOp->getOperand(1); 12368 EVT VT = SVOp->getValueType(0); 12369 int NumElems = VT.getVectorNumElements(); 12370 12371 if (V1.getOpcode() == ISD::CONCAT_VECTORS && 12372 V2.getOpcode() == ISD::CONCAT_VECTORS) { 12373 // 12374 // 0,0,0,... 12375 // | 12376 // V UNDEF BUILD_VECTOR UNDEF 12377 // \ / \ / 12378 // CONCAT_VECTOR CONCAT_VECTOR 12379 // \ / 12380 // \ / 12381 // RESULT: V + zero extended 12382 // 12383 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR || 12384 V2.getOperand(1).getOpcode() != ISD::UNDEF || 12385 V1.getOperand(1).getOpcode() != ISD::UNDEF) 12386 return SDValue(); 12387 12388 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode())) 12389 return SDValue(); 12390 12391 // To match the shuffle mask, the first half of the mask should 12392 // be exactly the first vector, and all the rest a splat with the 12393 // first element of the second one. 12394 for (int i = 0; i < NumElems/2; ++i) 12395 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) || 12396 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems)) 12397 return SDValue(); 12398 12399 // Emit a zeroed vector and insert the desired subvector on its 12400 // first half. 12401 SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl); 12402 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 12403 DAG.getConstant(0, MVT::i32), DAG, dl); 12404 return DCI.CombineTo(N, InsV); 12405 } 12406 12407 //===--------------------------------------------------------------------===// 12408 // Combine some shuffles into subvector extracts and inserts: 12409 // 12410 12411 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 12412 if (isShuffleHigh128VectorInsertLow(SVOp)) { 12413 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32), 12414 DAG, dl); 12415 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), 12416 V, DAG.getConstant(0, MVT::i32), DAG, dl); 12417 return DCI.CombineTo(N, InsV); 12418 } 12419 12420 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 12421 if (isShuffleLow128VectorInsertHigh(SVOp)) { 12422 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl); 12423 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), 12424 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl); 12425 return DCI.CombineTo(N, InsV); 12426 } 12427 12428 return SDValue(); 12429} 12430 12431/// PerformShuffleCombine - Performs several different shuffle combines. 12432static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG, 12433 TargetLowering::DAGCombinerInfo &DCI, 12434 const X86Subtarget *Subtarget) { 12435 DebugLoc dl = N->getDebugLoc(); 12436 EVT VT = N->getValueType(0); 12437 12438 // Don't create instructions with illegal types after legalize types has run. 12439 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12440 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType())) 12441 return SDValue(); 12442 12443 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode 12444 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 && 12445 N->getOpcode() == ISD::VECTOR_SHUFFLE) 12446 return PerformShuffleCombine256(N, DAG, DCI); 12447 12448 // Only handle 128 wide vector from here on. 12449 if (VT.getSizeInBits() != 128) 12450 return SDValue(); 12451 12452 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3, 12453 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are 12454 // consecutive, non-overlapping, and in the right order. 12455 SmallVector<SDValue, 16> Elts; 12456 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 12457 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0)); 12458 12459 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG); 12460} 12461 12462/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index 12463/// generation and convert it from being a bunch of shuffles and extracts 12464/// to a simple store and scalar loads to extract the elements. 12465static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG, 12466 const TargetLowering &TLI) { 12467 SDValue InputVector = N->getOperand(0); 12468 12469 // Only operate on vectors of 4 elements, where the alternative shuffling 12470 // gets to be more expensive. 12471 if (InputVector.getValueType() != MVT::v4i32) 12472 return SDValue(); 12473 12474 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a 12475 // single use which is a sign-extend or zero-extend, and all elements are 12476 // used. 12477 SmallVector<SDNode *, 4> Uses; 12478 unsigned ExtractedElements = 0; 12479 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(), 12480 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) { 12481 if (UI.getUse().getResNo() != InputVector.getResNo()) 12482 return SDValue(); 12483 12484 SDNode *Extract = *UI; 12485 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12486 return SDValue(); 12487 12488 if (Extract->getValueType(0) != MVT::i32) 12489 return SDValue(); 12490 if (!Extract->hasOneUse()) 12491 return SDValue(); 12492 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND && 12493 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND) 12494 return SDValue(); 12495 if (!isa<ConstantSDNode>(Extract->getOperand(1))) 12496 return SDValue(); 12497 12498 // Record which element was extracted. 12499 ExtractedElements |= 12500 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue(); 12501 12502 Uses.push_back(Extract); 12503 } 12504 12505 // If not all the elements were used, this may not be worthwhile. 12506 if (ExtractedElements != 15) 12507 return SDValue(); 12508 12509 // Ok, we've now decided to do the transformation. 12510 DebugLoc dl = InputVector.getDebugLoc(); 12511 12512 // Store the value to a temporary stack slot. 12513 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType()); 12514 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, 12515 MachinePointerInfo(), false, false, 0); 12516 12517 // Replace each use (extract) with a load of the appropriate element. 12518 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(), 12519 UE = Uses.end(); UI != UE; ++UI) { 12520 SDNode *Extract = *UI; 12521 12522 // cOMpute the element's address. 12523 SDValue Idx = Extract->getOperand(1); 12524 unsigned EltSize = 12525 InputVector.getValueType().getVectorElementType().getSizeInBits()/8; 12526 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(); 12527 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy()); 12528 12529 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 12530 StackPtr, OffsetVal); 12531 12532 // Load the scalar. 12533 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, 12534 ScalarAddr, MachinePointerInfo(), 12535 false, false, 0); 12536 12537 // Replace the exact with the load. 12538 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar); 12539 } 12540 12541 // The replacement was made in place; don't return anything. 12542 return SDValue(); 12543} 12544 12545/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes. 12546static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG, 12547 const X86Subtarget *Subtarget) { 12548 DebugLoc DL = N->getDebugLoc(); 12549 SDValue Cond = N->getOperand(0); 12550 // Get the LHS/RHS of the select. 12551 SDValue LHS = N->getOperand(1); 12552 SDValue RHS = N->getOperand(2); 12553 12554 // If we have SSE[12] support, try to form min/max nodes. SSE min/max 12555 // instructions match the semantics of the common C idiom x<y?x:y but not 12556 // x<=y?x:y, because of how they handle negative zero (which can be 12557 // ignored in unsafe-math mode). 12558 if (Subtarget->hasSSE2() && 12559 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) && 12560 Cond.getOpcode() == ISD::SETCC) { 12561 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 12562 12563 unsigned Opcode = 0; 12564 // Check for x CC y ? x : y. 12565 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 12566 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 12567 switch (CC) { 12568 default: break; 12569 case ISD::SETULT: 12570 // Converting this to a min would handle NaNs incorrectly, and swapping 12571 // the operands would cause it to handle comparisons between positive 12572 // and negative zero incorrectly. 12573 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 12574 if (!UnsafeFPMath && 12575 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 12576 break; 12577 std::swap(LHS, RHS); 12578 } 12579 Opcode = X86ISD::FMIN; 12580 break; 12581 case ISD::SETOLE: 12582 // Converting this to a min would handle comparisons between positive 12583 // and negative zero incorrectly. 12584 if (!UnsafeFPMath && 12585 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 12586 break; 12587 Opcode = X86ISD::FMIN; 12588 break; 12589 case ISD::SETULE: 12590 // Converting this to a min would handle both negative zeros and NaNs 12591 // incorrectly, but we can swap the operands to fix both. 12592 std::swap(LHS, RHS); 12593 case ISD::SETOLT: 12594 case ISD::SETLT: 12595 case ISD::SETLE: 12596 Opcode = X86ISD::FMIN; 12597 break; 12598 12599 case ISD::SETOGE: 12600 // Converting this to a max would handle comparisons between positive 12601 // and negative zero incorrectly. 12602 if (!UnsafeFPMath && 12603 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 12604 break; 12605 Opcode = X86ISD::FMAX; 12606 break; 12607 case ISD::SETUGT: 12608 // Converting this to a max would handle NaNs incorrectly, and swapping 12609 // the operands would cause it to handle comparisons between positive 12610 // and negative zero incorrectly. 12611 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 12612 if (!UnsafeFPMath && 12613 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 12614 break; 12615 std::swap(LHS, RHS); 12616 } 12617 Opcode = X86ISD::FMAX; 12618 break; 12619 case ISD::SETUGE: 12620 // Converting this to a max would handle both negative zeros and NaNs 12621 // incorrectly, but we can swap the operands to fix both. 12622 std::swap(LHS, RHS); 12623 case ISD::SETOGT: 12624 case ISD::SETGT: 12625 case ISD::SETGE: 12626 Opcode = X86ISD::FMAX; 12627 break; 12628 } 12629 // Check for x CC y ? y : x -- a min/max with reversed arms. 12630 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 12631 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 12632 switch (CC) { 12633 default: break; 12634 case ISD::SETOGE: 12635 // Converting this to a min would handle comparisons between positive 12636 // and negative zero incorrectly, and swapping the operands would 12637 // cause it to handle NaNs incorrectly. 12638 if (!UnsafeFPMath && 12639 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) { 12640 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 12641 break; 12642 std::swap(LHS, RHS); 12643 } 12644 Opcode = X86ISD::FMIN; 12645 break; 12646 case ISD::SETUGT: 12647 // Converting this to a min would handle NaNs incorrectly. 12648 if (!UnsafeFPMath && 12649 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) 12650 break; 12651 Opcode = X86ISD::FMIN; 12652 break; 12653 case ISD::SETUGE: 12654 // Converting this to a min would handle both negative zeros and NaNs 12655 // incorrectly, but we can swap the operands to fix both. 12656 std::swap(LHS, RHS); 12657 case ISD::SETOGT: 12658 case ISD::SETGT: 12659 case ISD::SETGE: 12660 Opcode = X86ISD::FMIN; 12661 break; 12662 12663 case ISD::SETULT: 12664 // Converting this to a max would handle NaNs incorrectly. 12665 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 12666 break; 12667 Opcode = X86ISD::FMAX; 12668 break; 12669 case ISD::SETOLE: 12670 // Converting this to a max would handle comparisons between positive 12671 // and negative zero incorrectly, and swapping the operands would 12672 // cause it to handle NaNs incorrectly. 12673 if (!UnsafeFPMath && 12674 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 12675 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 12676 break; 12677 std::swap(LHS, RHS); 12678 } 12679 Opcode = X86ISD::FMAX; 12680 break; 12681 case ISD::SETULE: 12682 // Converting this to a max would handle both negative zeros and NaNs 12683 // incorrectly, but we can swap the operands to fix both. 12684 std::swap(LHS, RHS); 12685 case ISD::SETOLT: 12686 case ISD::SETLT: 12687 case ISD::SETLE: 12688 Opcode = X86ISD::FMAX; 12689 break; 12690 } 12691 } 12692 12693 if (Opcode) 12694 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS); 12695 } 12696 12697 // If this is a select between two integer constants, try to do some 12698 // optimizations. 12699 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) { 12700 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS)) 12701 // Don't do this for crazy integer types. 12702 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) { 12703 // If this is efficiently invertible, canonicalize the LHSC/RHSC values 12704 // so that TrueC (the true value) is larger than FalseC. 12705 bool NeedsCondInvert = false; 12706 12707 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) && 12708 // Efficiently invertible. 12709 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible. 12710 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible. 12711 isa<ConstantSDNode>(Cond.getOperand(1))))) { 12712 NeedsCondInvert = true; 12713 std::swap(TrueC, FalseC); 12714 } 12715 12716 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0. 12717 if (FalseC->getAPIntValue() == 0 && 12718 TrueC->getAPIntValue().isPowerOf2()) { 12719 if (NeedsCondInvert) // Invert the condition if needed. 12720 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 12721 DAG.getConstant(1, Cond.getValueType())); 12722 12723 // Zero extend the condition if needed. 12724 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond); 12725 12726 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 12727 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond, 12728 DAG.getConstant(ShAmt, MVT::i8)); 12729 } 12730 12731 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. 12732 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 12733 if (NeedsCondInvert) // Invert the condition if needed. 12734 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 12735 DAG.getConstant(1, Cond.getValueType())); 12736 12737 // Zero extend the condition if needed. 12738 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 12739 FalseC->getValueType(0), Cond); 12740 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 12741 SDValue(FalseC, 0)); 12742 } 12743 12744 // Optimize cases that will turn into an LEA instruction. This requires 12745 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 12746 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 12747 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 12748 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 12749 12750 bool isFastMultiplier = false; 12751 if (Diff < 10) { 12752 switch ((unsigned char)Diff) { 12753 default: break; 12754 case 1: // result = add base, cond 12755 case 2: // result = lea base( , cond*2) 12756 case 3: // result = lea base(cond, cond*2) 12757 case 4: // result = lea base( , cond*4) 12758 case 5: // result = lea base(cond, cond*4) 12759 case 8: // result = lea base( , cond*8) 12760 case 9: // result = lea base(cond, cond*8) 12761 isFastMultiplier = true; 12762 break; 12763 } 12764 } 12765 12766 if (isFastMultiplier) { 12767 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 12768 if (NeedsCondInvert) // Invert the condition if needed. 12769 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 12770 DAG.getConstant(1, Cond.getValueType())); 12771 12772 // Zero extend the condition if needed. 12773 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 12774 Cond); 12775 // Scale the condition by the difference. 12776 if (Diff != 1) 12777 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 12778 DAG.getConstant(Diff, Cond.getValueType())); 12779 12780 // Add the base if non-zero. 12781 if (FalseC->getAPIntValue() != 0) 12782 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 12783 SDValue(FalseC, 0)); 12784 return Cond; 12785 } 12786 } 12787 } 12788 } 12789 12790 return SDValue(); 12791} 12792 12793/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL] 12794static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG, 12795 TargetLowering::DAGCombinerInfo &DCI) { 12796 DebugLoc DL = N->getDebugLoc(); 12797 12798 // If the flag operand isn't dead, don't touch this CMOV. 12799 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty()) 12800 return SDValue(); 12801 12802 SDValue FalseOp = N->getOperand(0); 12803 SDValue TrueOp = N->getOperand(1); 12804 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2); 12805 SDValue Cond = N->getOperand(3); 12806 if (CC == X86::COND_E || CC == X86::COND_NE) { 12807 switch (Cond.getOpcode()) { 12808 default: break; 12809 case X86ISD::BSR: 12810 case X86ISD::BSF: 12811 // If operand of BSR / BSF are proven never zero, then ZF cannot be set. 12812 if (DAG.isKnownNeverZero(Cond.getOperand(0))) 12813 return (CC == X86::COND_E) ? FalseOp : TrueOp; 12814 } 12815 } 12816 12817 // If this is a select between two integer constants, try to do some 12818 // optimizations. Note that the operands are ordered the opposite of SELECT 12819 // operands. 12820 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) { 12821 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) { 12822 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is 12823 // larger than FalseC (the false value). 12824 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) { 12825 CC = X86::GetOppositeBranchCondition(CC); 12826 std::swap(TrueC, FalseC); 12827 } 12828 12829 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0. 12830 // This is efficient for any integer data type (including i8/i16) and 12831 // shift amount. 12832 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) { 12833 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 12834 DAG.getConstant(CC, MVT::i8), Cond); 12835 12836 // Zero extend the condition if needed. 12837 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond); 12838 12839 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 12840 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond, 12841 DAG.getConstant(ShAmt, MVT::i8)); 12842 if (N->getNumValues() == 2) // Dead flag value? 12843 return DCI.CombineTo(N, Cond, SDValue()); 12844 return Cond; 12845 } 12846 12847 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient 12848 // for any integer data type, including i8/i16. 12849 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 12850 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 12851 DAG.getConstant(CC, MVT::i8), Cond); 12852 12853 // Zero extend the condition if needed. 12854 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 12855 FalseC->getValueType(0), Cond); 12856 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 12857 SDValue(FalseC, 0)); 12858 12859 if (N->getNumValues() == 2) // Dead flag value? 12860 return DCI.CombineTo(N, Cond, SDValue()); 12861 return Cond; 12862 } 12863 12864 // Optimize cases that will turn into an LEA instruction. This requires 12865 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 12866 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 12867 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 12868 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 12869 12870 bool isFastMultiplier = false; 12871 if (Diff < 10) { 12872 switch ((unsigned char)Diff) { 12873 default: break; 12874 case 1: // result = add base, cond 12875 case 2: // result = lea base( , cond*2) 12876 case 3: // result = lea base(cond, cond*2) 12877 case 4: // result = lea base( , cond*4) 12878 case 5: // result = lea base(cond, cond*4) 12879 case 8: // result = lea base( , cond*8) 12880 case 9: // result = lea base(cond, cond*8) 12881 isFastMultiplier = true; 12882 break; 12883 } 12884 } 12885 12886 if (isFastMultiplier) { 12887 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 12888 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 12889 DAG.getConstant(CC, MVT::i8), Cond); 12890 // Zero extend the condition if needed. 12891 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 12892 Cond); 12893 // Scale the condition by the difference. 12894 if (Diff != 1) 12895 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 12896 DAG.getConstant(Diff, Cond.getValueType())); 12897 12898 // Add the base if non-zero. 12899 if (FalseC->getAPIntValue() != 0) 12900 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 12901 SDValue(FalseC, 0)); 12902 if (N->getNumValues() == 2) // Dead flag value? 12903 return DCI.CombineTo(N, Cond, SDValue()); 12904 return Cond; 12905 } 12906 } 12907 } 12908 } 12909 return SDValue(); 12910} 12911 12912 12913/// PerformMulCombine - Optimize a single multiply with constant into two 12914/// in order to implement it with two cheaper instructions, e.g. 12915/// LEA + SHL, LEA + LEA. 12916static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG, 12917 TargetLowering::DAGCombinerInfo &DCI) { 12918 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 12919 return SDValue(); 12920 12921 EVT VT = N->getValueType(0); 12922 if (VT != MVT::i64) 12923 return SDValue(); 12924 12925 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12926 if (!C) 12927 return SDValue(); 12928 uint64_t MulAmt = C->getZExtValue(); 12929 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9) 12930 return SDValue(); 12931 12932 uint64_t MulAmt1 = 0; 12933 uint64_t MulAmt2 = 0; 12934 if ((MulAmt % 9) == 0) { 12935 MulAmt1 = 9; 12936 MulAmt2 = MulAmt / 9; 12937 } else if ((MulAmt % 5) == 0) { 12938 MulAmt1 = 5; 12939 MulAmt2 = MulAmt / 5; 12940 } else if ((MulAmt % 3) == 0) { 12941 MulAmt1 = 3; 12942 MulAmt2 = MulAmt / 3; 12943 } 12944 if (MulAmt2 && 12945 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){ 12946 DebugLoc DL = N->getDebugLoc(); 12947 12948 if (isPowerOf2_64(MulAmt2) && 12949 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD)) 12950 // If second multiplifer is pow2, issue it first. We want the multiply by 12951 // 3, 5, or 9 to be folded into the addressing mode unless the lone use 12952 // is an add. 12953 std::swap(MulAmt1, MulAmt2); 12954 12955 SDValue NewMul; 12956 if (isPowerOf2_64(MulAmt1)) 12957 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 12958 DAG.getConstant(Log2_64(MulAmt1), MVT::i8)); 12959 else 12960 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0), 12961 DAG.getConstant(MulAmt1, VT)); 12962 12963 if (isPowerOf2_64(MulAmt2)) 12964 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul, 12965 DAG.getConstant(Log2_64(MulAmt2), MVT::i8)); 12966 else 12967 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul, 12968 DAG.getConstant(MulAmt2, VT)); 12969 12970 // Do not add new nodes to DAG combiner worklist. 12971 DCI.CombineTo(N, NewMul, false); 12972 } 12973 return SDValue(); 12974} 12975 12976static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) { 12977 SDValue N0 = N->getOperand(0); 12978 SDValue N1 = N->getOperand(1); 12979 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 12980 EVT VT = N0.getValueType(); 12981 12982 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2)) 12983 // since the result of setcc_c is all zero's or all ones. 12984 if (N1C && N0.getOpcode() == ISD::AND && 12985 N0.getOperand(1).getOpcode() == ISD::Constant) { 12986 SDValue N00 = N0.getOperand(0); 12987 if (N00.getOpcode() == X86ISD::SETCC_CARRY || 12988 ((N00.getOpcode() == ISD::ANY_EXTEND || 12989 N00.getOpcode() == ISD::ZERO_EXTEND) && 12990 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) { 12991 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 12992 APInt ShAmt = N1C->getAPIntValue(); 12993 Mask = Mask.shl(ShAmt); 12994 if (Mask != 0) 12995 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 12996 N00, DAG.getConstant(Mask, VT)); 12997 } 12998 } 12999 13000 return SDValue(); 13001} 13002 13003/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts 13004/// when possible. 13005static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG, 13006 const X86Subtarget *Subtarget) { 13007 EVT VT = N->getValueType(0); 13008 if (!VT.isVector() && VT.isInteger() && 13009 N->getOpcode() == ISD::SHL) 13010 return PerformSHLCombine(N, DAG); 13011 13012 // On X86 with SSE2 support, we can transform this to a vector shift if 13013 // all elements are shifted by the same amount. We can't do this in legalize 13014 // because the a constant vector is typically transformed to a constant pool 13015 // so we have no knowledge of the shift amount. 13016 if (!(Subtarget->hasSSE2() || Subtarget->hasAVX())) 13017 return SDValue(); 13018 13019 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16) 13020 return SDValue(); 13021 13022 SDValue ShAmtOp = N->getOperand(1); 13023 EVT EltVT = VT.getVectorElementType(); 13024 DebugLoc DL = N->getDebugLoc(); 13025 SDValue BaseShAmt = SDValue(); 13026 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) { 13027 unsigned NumElts = VT.getVectorNumElements(); 13028 unsigned i = 0; 13029 for (; i != NumElts; ++i) { 13030 SDValue Arg = ShAmtOp.getOperand(i); 13031 if (Arg.getOpcode() == ISD::UNDEF) continue; 13032 BaseShAmt = Arg; 13033 break; 13034 } 13035 for (; i != NumElts; ++i) { 13036 SDValue Arg = ShAmtOp.getOperand(i); 13037 if (Arg.getOpcode() == ISD::UNDEF) continue; 13038 if (Arg != BaseShAmt) { 13039 return SDValue(); 13040 } 13041 } 13042 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE && 13043 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) { 13044 SDValue InVec = ShAmtOp.getOperand(0); 13045 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 13046 unsigned NumElts = InVec.getValueType().getVectorNumElements(); 13047 unsigned i = 0; 13048 for (; i != NumElts; ++i) { 13049 SDValue Arg = InVec.getOperand(i); 13050 if (Arg.getOpcode() == ISD::UNDEF) continue; 13051 BaseShAmt = Arg; 13052 break; 13053 } 13054 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) { 13055 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) { 13056 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex(); 13057 if (C->getZExtValue() == SplatIdx) 13058 BaseShAmt = InVec.getOperand(1); 13059 } 13060 } 13061 if (BaseShAmt.getNode() == 0) 13062 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp, 13063 DAG.getIntPtrConstant(0)); 13064 } else 13065 return SDValue(); 13066 13067 // The shift amount is an i32. 13068 if (EltVT.bitsGT(MVT::i32)) 13069 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt); 13070 else if (EltVT.bitsLT(MVT::i32)) 13071 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt); 13072 13073 // The shift amount is identical so we can do a vector shift. 13074 SDValue ValOp = N->getOperand(0); 13075 switch (N->getOpcode()) { 13076 default: 13077 llvm_unreachable("Unknown shift opcode!"); 13078 break; 13079 case ISD::SHL: 13080 if (VT == MVT::v2i64) 13081 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13082 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 13083 ValOp, BaseShAmt); 13084 if (VT == MVT::v4i32) 13085 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13086 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 13087 ValOp, BaseShAmt); 13088 if (VT == MVT::v8i16) 13089 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13090 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 13091 ValOp, BaseShAmt); 13092 break; 13093 case ISD::SRA: 13094 if (VT == MVT::v4i32) 13095 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13096 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32), 13097 ValOp, BaseShAmt); 13098 if (VT == MVT::v8i16) 13099 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13100 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32), 13101 ValOp, BaseShAmt); 13102 break; 13103 case ISD::SRL: 13104 if (VT == MVT::v2i64) 13105 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13106 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 13107 ValOp, BaseShAmt); 13108 if (VT == MVT::v4i32) 13109 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13110 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32), 13111 ValOp, BaseShAmt); 13112 if (VT == MVT::v8i16) 13113 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13114 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 13115 ValOp, BaseShAmt); 13116 break; 13117 } 13118 return SDValue(); 13119} 13120 13121 13122// CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..)) 13123// where both setccs reference the same FP CMP, and rewrite for CMPEQSS 13124// and friends. Likewise for OR -> CMPNEQSS. 13125static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG, 13126 TargetLowering::DAGCombinerInfo &DCI, 13127 const X86Subtarget *Subtarget) { 13128 unsigned opcode; 13129 13130 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but 13131 // we're requiring SSE2 for both. 13132 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) { 13133 SDValue N0 = N->getOperand(0); 13134 SDValue N1 = N->getOperand(1); 13135 SDValue CMP0 = N0->getOperand(1); 13136 SDValue CMP1 = N1->getOperand(1); 13137 DebugLoc DL = N->getDebugLoc(); 13138 13139 // The SETCCs should both refer to the same CMP. 13140 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1) 13141 return SDValue(); 13142 13143 SDValue CMP00 = CMP0->getOperand(0); 13144 SDValue CMP01 = CMP0->getOperand(1); 13145 EVT VT = CMP00.getValueType(); 13146 13147 if (VT == MVT::f32 || VT == MVT::f64) { 13148 bool ExpectingFlags = false; 13149 // Check for any users that want flags: 13150 for (SDNode::use_iterator UI = N->use_begin(), 13151 UE = N->use_end(); 13152 !ExpectingFlags && UI != UE; ++UI) 13153 switch (UI->getOpcode()) { 13154 default: 13155 case ISD::BR_CC: 13156 case ISD::BRCOND: 13157 case ISD::SELECT: 13158 ExpectingFlags = true; 13159 break; 13160 case ISD::CopyToReg: 13161 case ISD::SIGN_EXTEND: 13162 case ISD::ZERO_EXTEND: 13163 case ISD::ANY_EXTEND: 13164 break; 13165 } 13166 13167 if (!ExpectingFlags) { 13168 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0); 13169 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0); 13170 13171 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) { 13172 X86::CondCode tmp = cc0; 13173 cc0 = cc1; 13174 cc1 = tmp; 13175 } 13176 13177 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) || 13178 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) { 13179 bool is64BitFP = (CMP00.getValueType() == MVT::f64); 13180 X86ISD::NodeType NTOperator = is64BitFP ? 13181 X86ISD::FSETCCsd : X86ISD::FSETCCss; 13182 // FIXME: need symbolic constants for these magic numbers. 13183 // See X86ATTInstPrinter.cpp:printSSECC(). 13184 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4; 13185 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01, 13186 DAG.getConstant(x86cc, MVT::i8)); 13187 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32, 13188 OnesOrZeroesF); 13189 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI, 13190 DAG.getConstant(1, MVT::i32)); 13191 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed); 13192 return OneBitOfTruth; 13193 } 13194 } 13195 } 13196 } 13197 return SDValue(); 13198} 13199 13200/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector 13201/// so it can be folded inside ANDNP. 13202static bool CanFoldXORWithAllOnes(const SDNode *N) { 13203 EVT VT = N->getValueType(0); 13204 13205 // Match direct AllOnes for 128 and 256-bit vectors 13206 if (ISD::isBuildVectorAllOnes(N)) 13207 return true; 13208 13209 // Look through a bit convert. 13210 if (N->getOpcode() == ISD::BITCAST) 13211 N = N->getOperand(0).getNode(); 13212 13213 // Sometimes the operand may come from a insert_subvector building a 256-bit 13214 // allones vector 13215 if (VT.getSizeInBits() == 256 && 13216 N->getOpcode() == ISD::INSERT_SUBVECTOR) { 13217 SDValue V1 = N->getOperand(0); 13218 SDValue V2 = N->getOperand(1); 13219 13220 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR && 13221 V1.getOperand(0).getOpcode() == ISD::UNDEF && 13222 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) && 13223 ISD::isBuildVectorAllOnes(V2.getNode())) 13224 return true; 13225 } 13226 13227 return false; 13228} 13229 13230static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG, 13231 TargetLowering::DAGCombinerInfo &DCI, 13232 const X86Subtarget *Subtarget) { 13233 if (DCI.isBeforeLegalizeOps()) 13234 return SDValue(); 13235 13236 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 13237 if (R.getNode()) 13238 return R; 13239 13240 // Want to form ANDNP nodes: 13241 // 1) In the hopes of then easily combining them with OR and AND nodes 13242 // to form PBLEND/PSIGN. 13243 // 2) To match ANDN packed intrinsics 13244 EVT VT = N->getValueType(0); 13245 if (VT != MVT::v2i64 && VT != MVT::v4i64) 13246 return SDValue(); 13247 13248 SDValue N0 = N->getOperand(0); 13249 SDValue N1 = N->getOperand(1); 13250 DebugLoc DL = N->getDebugLoc(); 13251 13252 // Check LHS for vnot 13253 if (N0.getOpcode() == ISD::XOR && 13254 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) 13255 CanFoldXORWithAllOnes(N0.getOperand(1).getNode())) 13256 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1); 13257 13258 // Check RHS for vnot 13259 if (N1.getOpcode() == ISD::XOR && 13260 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) 13261 CanFoldXORWithAllOnes(N1.getOperand(1).getNode())) 13262 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0); 13263 13264 return SDValue(); 13265} 13266 13267static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG, 13268 TargetLowering::DAGCombinerInfo &DCI, 13269 const X86Subtarget *Subtarget) { 13270 if (DCI.isBeforeLegalizeOps()) 13271 return SDValue(); 13272 13273 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 13274 if (R.getNode()) 13275 return R; 13276 13277 EVT VT = N->getValueType(0); 13278 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64) 13279 return SDValue(); 13280 13281 SDValue N0 = N->getOperand(0); 13282 SDValue N1 = N->getOperand(1); 13283 13284 // look for psign/blend 13285 if (Subtarget->hasSSSE3()) { 13286 if (VT == MVT::v2i64) { 13287 // Canonicalize pandn to RHS 13288 if (N0.getOpcode() == X86ISD::ANDNP) 13289 std::swap(N0, N1); 13290 // or (and (m, x), (pandn m, y)) 13291 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) { 13292 SDValue Mask = N1.getOperand(0); 13293 SDValue X = N1.getOperand(1); 13294 SDValue Y; 13295 if (N0.getOperand(0) == Mask) 13296 Y = N0.getOperand(1); 13297 if (N0.getOperand(1) == Mask) 13298 Y = N0.getOperand(0); 13299 13300 // Check to see if the mask appeared in both the AND and ANDNP and 13301 if (!Y.getNode()) 13302 return SDValue(); 13303 13304 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them. 13305 if (Mask.getOpcode() != ISD::BITCAST || 13306 X.getOpcode() != ISD::BITCAST || 13307 Y.getOpcode() != ISD::BITCAST) 13308 return SDValue(); 13309 13310 // Look through mask bitcast. 13311 Mask = Mask.getOperand(0); 13312 EVT MaskVT = Mask.getValueType(); 13313 13314 // Validate that the Mask operand is a vector sra node. The sra node 13315 // will be an intrinsic. 13316 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN) 13317 return SDValue(); 13318 13319 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but 13320 // there is no psrai.b 13321 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) { 13322 case Intrinsic::x86_sse2_psrai_w: 13323 case Intrinsic::x86_sse2_psrai_d: 13324 break; 13325 default: return SDValue(); 13326 } 13327 13328 // Check that the SRA is all signbits. 13329 SDValue SraC = Mask.getOperand(2); 13330 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue(); 13331 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits(); 13332 if ((SraAmt + 1) != EltBits) 13333 return SDValue(); 13334 13335 DebugLoc DL = N->getDebugLoc(); 13336 13337 // Now we know we at least have a plendvb with the mask val. See if 13338 // we can form a psignb/w/d. 13339 // psign = x.type == y.type == mask.type && y = sub(0, x); 13340 X = X.getOperand(0); 13341 Y = Y.getOperand(0); 13342 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X && 13343 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) && 13344 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){ 13345 unsigned Opc = 0; 13346 switch (EltBits) { 13347 case 8: Opc = X86ISD::PSIGNB; break; 13348 case 16: Opc = X86ISD::PSIGNW; break; 13349 case 32: Opc = X86ISD::PSIGND; break; 13350 default: break; 13351 } 13352 if (Opc) { 13353 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1)); 13354 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign); 13355 } 13356 } 13357 // PBLENDVB only available on SSE 4.1 13358 if (!Subtarget->hasSSE41()) 13359 return SDValue(); 13360 13361 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X); 13362 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y); 13363 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask); 13364 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask); 13365 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask); 13366 } 13367 } 13368 } 13369 13370 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c) 13371 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 13372 std::swap(N0, N1); 13373 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 13374 return SDValue(); 13375 if (!N0.hasOneUse() || !N1.hasOneUse()) 13376 return SDValue(); 13377 13378 SDValue ShAmt0 = N0.getOperand(1); 13379 if (ShAmt0.getValueType() != MVT::i8) 13380 return SDValue(); 13381 SDValue ShAmt1 = N1.getOperand(1); 13382 if (ShAmt1.getValueType() != MVT::i8) 13383 return SDValue(); 13384 if (ShAmt0.getOpcode() == ISD::TRUNCATE) 13385 ShAmt0 = ShAmt0.getOperand(0); 13386 if (ShAmt1.getOpcode() == ISD::TRUNCATE) 13387 ShAmt1 = ShAmt1.getOperand(0); 13388 13389 DebugLoc DL = N->getDebugLoc(); 13390 unsigned Opc = X86ISD::SHLD; 13391 SDValue Op0 = N0.getOperand(0); 13392 SDValue Op1 = N1.getOperand(0); 13393 if (ShAmt0.getOpcode() == ISD::SUB) { 13394 Opc = X86ISD::SHRD; 13395 std::swap(Op0, Op1); 13396 std::swap(ShAmt0, ShAmt1); 13397 } 13398 13399 unsigned Bits = VT.getSizeInBits(); 13400 if (ShAmt1.getOpcode() == ISD::SUB) { 13401 SDValue Sum = ShAmt1.getOperand(0); 13402 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) { 13403 SDValue ShAmt1Op1 = ShAmt1.getOperand(1); 13404 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE) 13405 ShAmt1Op1 = ShAmt1Op1.getOperand(0); 13406 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0) 13407 return DAG.getNode(Opc, DL, VT, 13408 Op0, Op1, 13409 DAG.getNode(ISD::TRUNCATE, DL, 13410 MVT::i8, ShAmt0)); 13411 } 13412 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) { 13413 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0); 13414 if (ShAmt0C && 13415 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits) 13416 return DAG.getNode(Opc, DL, VT, 13417 N0.getOperand(0), N1.getOperand(0), 13418 DAG.getNode(ISD::TRUNCATE, DL, 13419 MVT::i8, ShAmt0)); 13420 } 13421 13422 return SDValue(); 13423} 13424 13425/// PerformSTORECombine - Do target-specific dag combines on STORE nodes. 13426static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG, 13427 const X86Subtarget *Subtarget) { 13428 StoreSDNode *St = cast<StoreSDNode>(N); 13429 EVT VT = St->getValue().getValueType(); 13430 EVT StVT = St->getMemoryVT(); 13431 DebugLoc dl = St->getDebugLoc(); 13432 SDValue StoredVal = St->getOperand(1); 13433 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13434 13435 // If we are saving a concatination of two XMM registers, perform two stores. 13436 // This is better in Sandy Bridge cause one 256-bit mem op is done via two 13437 // 128-bit ones. If in the future the cost becomes only one memory access the 13438 // first version would be better. 13439 if (VT.getSizeInBits() == 256 && 13440 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS && 13441 StoredVal.getNumOperands() == 2) { 13442 13443 SDValue Value0 = StoredVal.getOperand(0); 13444 SDValue Value1 = StoredVal.getOperand(1); 13445 13446 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy()); 13447 SDValue Ptr0 = St->getBasePtr(); 13448 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride); 13449 13450 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0, 13451 St->getPointerInfo(), St->isVolatile(), 13452 St->isNonTemporal(), St->getAlignment()); 13453 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1, 13454 St->getPointerInfo(), St->isVolatile(), 13455 St->isNonTemporal(), St->getAlignment()); 13456 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1); 13457 } 13458 13459 // Optimize trunc store (of multiple scalars) to shuffle and store. 13460 // First, pack all of the elements in one place. Next, store to memory 13461 // in fewer chunks. 13462 if (St->isTruncatingStore() && VT.isVector()) { 13463 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13464 unsigned NumElems = VT.getVectorNumElements(); 13465 assert(StVT != VT && "Cannot truncate to the same type"); 13466 unsigned FromSz = VT.getVectorElementType().getSizeInBits(); 13467 unsigned ToSz = StVT.getVectorElementType().getSizeInBits(); 13468 13469 // From, To sizes and ElemCount must be pow of two 13470 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue(); 13471 // We are going to use the original vector elt for storing. 13472 // accumulated smaller vector elements must be a multiple of bigger size. 13473 if (0 != (NumElems * ToSz) % FromSz) return SDValue(); 13474 unsigned SizeRatio = FromSz / ToSz; 13475 13476 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits()); 13477 13478 // Create a type on which we perform the shuffle 13479 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), 13480 StVT.getScalarType(), NumElems*SizeRatio); 13481 13482 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 13483 13484 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue()); 13485 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 13486 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio; 13487 13488 // Can't shuffle using an illegal type 13489 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 13490 13491 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec, 13492 DAG.getUNDEF(WideVec.getValueType()), 13493 ShuffleVec.data()); 13494 // At this point all of the data is stored at the bottom of the 13495 // register. We now need to save it to mem. 13496 13497 // Find the largest store unit 13498 MVT StoreType = MVT::i8; 13499 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 13500 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 13501 MVT Tp = (MVT::SimpleValueType)tp; 13502 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz) 13503 StoreType = Tp; 13504 } 13505 13506 // Bitcast the original vector into a vector of store-size units 13507 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 13508 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 13509 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 13510 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff); 13511 SmallVector<SDValue, 8> Chains; 13512 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, 13513 TLI.getPointerTy()); 13514 SDValue Ptr = St->getBasePtr(); 13515 13516 // Perform one or more big stores into memory. 13517 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) { 13518 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 13519 StoreType, ShuffWide, 13520 DAG.getIntPtrConstant(i)); 13521 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr, 13522 St->getPointerInfo(), St->isVolatile(), 13523 St->isNonTemporal(), St->getAlignment()); 13524 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13525 Chains.push_back(Ch); 13526 } 13527 13528 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 13529 Chains.size()); 13530 } 13531 13532 13533 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering 13534 // the FP state in cases where an emms may be missing. 13535 // A preferable solution to the general problem is to figure out the right 13536 // places to insert EMMS. This qualifies as a quick hack. 13537 13538 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode. 13539 if (VT.getSizeInBits() != 64) 13540 return SDValue(); 13541 13542 const Function *F = DAG.getMachineFunction().getFunction(); 13543 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat); 13544 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps 13545 && Subtarget->hasSSE2(); 13546 if ((VT.isVector() || 13547 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) && 13548 isa<LoadSDNode>(St->getValue()) && 13549 !cast<LoadSDNode>(St->getValue())->isVolatile() && 13550 St->getChain().hasOneUse() && !St->isVolatile()) { 13551 SDNode* LdVal = St->getValue().getNode(); 13552 LoadSDNode *Ld = 0; 13553 int TokenFactorIndex = -1; 13554 SmallVector<SDValue, 8> Ops; 13555 SDNode* ChainVal = St->getChain().getNode(); 13556 // Must be a store of a load. We currently handle two cases: the load 13557 // is a direct child, and it's under an intervening TokenFactor. It is 13558 // possible to dig deeper under nested TokenFactors. 13559 if (ChainVal == LdVal) 13560 Ld = cast<LoadSDNode>(St->getChain()); 13561 else if (St->getValue().hasOneUse() && 13562 ChainVal->getOpcode() == ISD::TokenFactor) { 13563 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) { 13564 if (ChainVal->getOperand(i).getNode() == LdVal) { 13565 TokenFactorIndex = i; 13566 Ld = cast<LoadSDNode>(St->getValue()); 13567 } else 13568 Ops.push_back(ChainVal->getOperand(i)); 13569 } 13570 } 13571 13572 if (!Ld || !ISD::isNormalLoad(Ld)) 13573 return SDValue(); 13574 13575 // If this is not the MMX case, i.e. we are just turning i64 load/store 13576 // into f64 load/store, avoid the transformation if there are multiple 13577 // uses of the loaded value. 13578 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0)) 13579 return SDValue(); 13580 13581 DebugLoc LdDL = Ld->getDebugLoc(); 13582 DebugLoc StDL = N->getDebugLoc(); 13583 // If we are a 64-bit capable x86, lower to a single movq load/store pair. 13584 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store 13585 // pair instead. 13586 if (Subtarget->is64Bit() || F64IsLegal) { 13587 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64; 13588 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(), 13589 Ld->getPointerInfo(), Ld->isVolatile(), 13590 Ld->isNonTemporal(), Ld->getAlignment()); 13591 SDValue NewChain = NewLd.getValue(1); 13592 if (TokenFactorIndex != -1) { 13593 Ops.push_back(NewChain); 13594 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 13595 Ops.size()); 13596 } 13597 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(), 13598 St->getPointerInfo(), 13599 St->isVolatile(), St->isNonTemporal(), 13600 St->getAlignment()); 13601 } 13602 13603 // Otherwise, lower to two pairs of 32-bit loads / stores. 13604 SDValue LoAddr = Ld->getBasePtr(); 13605 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr, 13606 DAG.getConstant(4, MVT::i32)); 13607 13608 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr, 13609 Ld->getPointerInfo(), 13610 Ld->isVolatile(), Ld->isNonTemporal(), 13611 Ld->getAlignment()); 13612 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr, 13613 Ld->getPointerInfo().getWithOffset(4), 13614 Ld->isVolatile(), Ld->isNonTemporal(), 13615 MinAlign(Ld->getAlignment(), 4)); 13616 13617 SDValue NewChain = LoLd.getValue(1); 13618 if (TokenFactorIndex != -1) { 13619 Ops.push_back(LoLd); 13620 Ops.push_back(HiLd); 13621 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 13622 Ops.size()); 13623 } 13624 13625 LoAddr = St->getBasePtr(); 13626 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr, 13627 DAG.getConstant(4, MVT::i32)); 13628 13629 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr, 13630 St->getPointerInfo(), 13631 St->isVolatile(), St->isNonTemporal(), 13632 St->getAlignment()); 13633 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr, 13634 St->getPointerInfo().getWithOffset(4), 13635 St->isVolatile(), 13636 St->isNonTemporal(), 13637 MinAlign(St->getAlignment(), 4)); 13638 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt); 13639 } 13640 return SDValue(); 13641} 13642 13643/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and 13644/// X86ISD::FXOR nodes. 13645static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) { 13646 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR); 13647 // F[X]OR(0.0, x) -> x 13648 // F[X]OR(x, 0.0) -> x 13649 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 13650 if (C->getValueAPF().isPosZero()) 13651 return N->getOperand(1); 13652 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 13653 if (C->getValueAPF().isPosZero()) 13654 return N->getOperand(0); 13655 return SDValue(); 13656} 13657 13658/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes. 13659static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) { 13660 // FAND(0.0, x) -> 0.0 13661 // FAND(x, 0.0) -> 0.0 13662 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 13663 if (C->getValueAPF().isPosZero()) 13664 return N->getOperand(0); 13665 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 13666 if (C->getValueAPF().isPosZero()) 13667 return N->getOperand(1); 13668 return SDValue(); 13669} 13670 13671static SDValue PerformBTCombine(SDNode *N, 13672 SelectionDAG &DAG, 13673 TargetLowering::DAGCombinerInfo &DCI) { 13674 // BT ignores high bits in the bit index operand. 13675 SDValue Op1 = N->getOperand(1); 13676 if (Op1.hasOneUse()) { 13677 unsigned BitWidth = Op1.getValueSizeInBits(); 13678 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth)); 13679 APInt KnownZero, KnownOne; 13680 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 13681 !DCI.isBeforeLegalizeOps()); 13682 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13683 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) || 13684 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO)) 13685 DCI.CommitTargetLoweringOpt(TLO); 13686 } 13687 return SDValue(); 13688} 13689 13690static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) { 13691 SDValue Op = N->getOperand(0); 13692 if (Op.getOpcode() == ISD::BITCAST) 13693 Op = Op.getOperand(0); 13694 EVT VT = N->getValueType(0), OpVT = Op.getValueType(); 13695 if (Op.getOpcode() == X86ISD::VZEXT_LOAD && 13696 VT.getVectorElementType().getSizeInBits() == 13697 OpVT.getVectorElementType().getSizeInBits()) { 13698 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op); 13699 } 13700 return SDValue(); 13701} 13702 13703static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) { 13704 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) -> 13705 // (and (i32 x86isd::setcc_carry), 1) 13706 // This eliminates the zext. This transformation is necessary because 13707 // ISD::SETCC is always legalized to i8. 13708 DebugLoc dl = N->getDebugLoc(); 13709 SDValue N0 = N->getOperand(0); 13710 EVT VT = N->getValueType(0); 13711 if (N0.getOpcode() == ISD::AND && 13712 N0.hasOneUse() && 13713 N0.getOperand(0).hasOneUse()) { 13714 SDValue N00 = N0.getOperand(0); 13715 if (N00.getOpcode() != X86ISD::SETCC_CARRY) 13716 return SDValue(); 13717 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 13718 if (!C || C->getZExtValue() != 1) 13719 return SDValue(); 13720 return DAG.getNode(ISD::AND, dl, VT, 13721 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, 13722 N00.getOperand(0), N00.getOperand(1)), 13723 DAG.getConstant(1, VT)); 13724 } 13725 13726 return SDValue(); 13727} 13728 13729// Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT 13730static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) { 13731 unsigned X86CC = N->getConstantOperandVal(0); 13732 SDValue EFLAG = N->getOperand(1); 13733 DebugLoc DL = N->getDebugLoc(); 13734 13735 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without 13736 // a zext and produces an all-ones bit which is more useful than 0/1 in some 13737 // cases. 13738 if (X86CC == X86::COND_B) 13739 return DAG.getNode(ISD::AND, DL, MVT::i8, 13740 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8, 13741 DAG.getConstant(X86CC, MVT::i8), EFLAG), 13742 DAG.getConstant(1, MVT::i8)); 13743 13744 return SDValue(); 13745} 13746 13747static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, 13748 const X86TargetLowering *XTLI) { 13749 SDValue Op0 = N->getOperand(0); 13750 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have 13751 // a 32-bit target where SSE doesn't support i64->FP operations. 13752 if (Op0.getOpcode() == ISD::LOAD) { 13753 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode()); 13754 EVT VT = Ld->getValueType(0); 13755 if (!Ld->isVolatile() && !N->getValueType(0).isVector() && 13756 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() && 13757 !XTLI->getSubtarget()->is64Bit() && 13758 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 13759 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0), 13760 Ld->getChain(), Op0, DAG); 13761 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1)); 13762 return FILDChain; 13763 } 13764 } 13765 return SDValue(); 13766} 13767 13768// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS 13769static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG, 13770 X86TargetLowering::DAGCombinerInfo &DCI) { 13771 // If the LHS and RHS of the ADC node are zero, then it can't overflow and 13772 // the result is either zero or one (depending on the input carry bit). 13773 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1. 13774 if (X86::isZeroNode(N->getOperand(0)) && 13775 X86::isZeroNode(N->getOperand(1)) && 13776 // We don't have a good way to replace an EFLAGS use, so only do this when 13777 // dead right now. 13778 SDValue(N, 1).use_empty()) { 13779 DebugLoc DL = N->getDebugLoc(); 13780 EVT VT = N->getValueType(0); 13781 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1)); 13782 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT, 13783 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, 13784 DAG.getConstant(X86::COND_B,MVT::i8), 13785 N->getOperand(2)), 13786 DAG.getConstant(1, VT)); 13787 return DCI.CombineTo(N, Res1, CarryOut); 13788 } 13789 13790 return SDValue(); 13791} 13792 13793// fold (add Y, (sete X, 0)) -> adc 0, Y 13794// (add Y, (setne X, 0)) -> sbb -1, Y 13795// (sub (sete X, 0), Y) -> sbb 0, Y 13796// (sub (setne X, 0), Y) -> adc -1, Y 13797static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) { 13798 DebugLoc DL = N->getDebugLoc(); 13799 13800 // Look through ZExts. 13801 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0); 13802 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse()) 13803 return SDValue(); 13804 13805 SDValue SetCC = Ext.getOperand(0); 13806 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse()) 13807 return SDValue(); 13808 13809 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0); 13810 if (CC != X86::COND_E && CC != X86::COND_NE) 13811 return SDValue(); 13812 13813 SDValue Cmp = SetCC.getOperand(1); 13814 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() || 13815 !X86::isZeroNode(Cmp.getOperand(1)) || 13816 !Cmp.getOperand(0).getValueType().isInteger()) 13817 return SDValue(); 13818 13819 SDValue CmpOp0 = Cmp.getOperand(0); 13820 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0, 13821 DAG.getConstant(1, CmpOp0.getValueType())); 13822 13823 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1); 13824 if (CC == X86::COND_NE) 13825 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB, 13826 DL, OtherVal.getValueType(), OtherVal, 13827 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp); 13828 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC, 13829 DL, OtherVal.getValueType(), OtherVal, 13830 DAG.getConstant(0, OtherVal.getValueType()), NewCmp); 13831} 13832 13833static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) { 13834 SDValue Op0 = N->getOperand(0); 13835 SDValue Op1 = N->getOperand(1); 13836 13837 // X86 can't encode an immediate LHS of a sub. See if we can push the 13838 // negation into a preceding instruction. 13839 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) { 13840 // If the RHS of the sub is a XOR with one use and a constant, invert the 13841 // immediate. Then add one to the LHS of the sub so we can turn 13842 // X-Y -> X+~Y+1, saving one register. 13843 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR && 13844 isa<ConstantSDNode>(Op1.getOperand(1))) { 13845 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue(); 13846 EVT VT = Op0.getValueType(); 13847 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT, 13848 Op1.getOperand(0), 13849 DAG.getConstant(~XorC, VT)); 13850 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor, 13851 DAG.getConstant(C->getAPIntValue()+1, VT)); 13852 } 13853 } 13854 13855 return OptimizeConditionalInDecrement(N, DAG); 13856} 13857 13858SDValue X86TargetLowering::PerformDAGCombine(SDNode *N, 13859 DAGCombinerInfo &DCI) const { 13860 SelectionDAG &DAG = DCI.DAG; 13861 switch (N->getOpcode()) { 13862 default: break; 13863 case ISD::EXTRACT_VECTOR_ELT: 13864 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this); 13865 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget); 13866 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI); 13867 case ISD::ADD: return OptimizeConditionalInDecrement(N, DAG); 13868 case ISD::SUB: return PerformSubCombine(N, DAG); 13869 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI); 13870 case ISD::MUL: return PerformMulCombine(N, DAG, DCI); 13871 case ISD::SHL: 13872 case ISD::SRA: 13873 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget); 13874 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget); 13875 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget); 13876 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget); 13877 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this); 13878 case X86ISD::FXOR: 13879 case X86ISD::FOR: return PerformFORCombine(N, DAG); 13880 case X86ISD::FAND: return PerformFANDCombine(N, DAG); 13881 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI); 13882 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG); 13883 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG); 13884 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG); 13885 case X86ISD::SHUFPS: // Handle all target specific shuffles 13886 case X86ISD::SHUFPD: 13887 case X86ISD::PALIGN: 13888 case X86ISD::PUNPCKHBW: 13889 case X86ISD::PUNPCKHWD: 13890 case X86ISD::PUNPCKHDQ: 13891 case X86ISD::PUNPCKHQDQ: 13892 case X86ISD::UNPCKHPS: 13893 case X86ISD::UNPCKHPD: 13894 case X86ISD::VUNPCKHPSY: 13895 case X86ISD::VUNPCKHPDY: 13896 case X86ISD::PUNPCKLBW: 13897 case X86ISD::PUNPCKLWD: 13898 case X86ISD::PUNPCKLDQ: 13899 case X86ISD::PUNPCKLQDQ: 13900 case X86ISD::UNPCKLPS: 13901 case X86ISD::UNPCKLPD: 13902 case X86ISD::VUNPCKLPSY: 13903 case X86ISD::VUNPCKLPDY: 13904 case X86ISD::MOVHLPS: 13905 case X86ISD::MOVLHPS: 13906 case X86ISD::PSHUFD: 13907 case X86ISD::PSHUFHW: 13908 case X86ISD::PSHUFLW: 13909 case X86ISD::MOVSS: 13910 case X86ISD::MOVSD: 13911 case X86ISD::VPERMILPS: 13912 case X86ISD::VPERMILPSY: 13913 case X86ISD::VPERMILPD: 13914 case X86ISD::VPERMILPDY: 13915 case X86ISD::VPERM2F128: 13916 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget); 13917 } 13918 13919 return SDValue(); 13920} 13921 13922/// isTypeDesirableForOp - Return true if the target has native support for 13923/// the specified value type and it is 'desirable' to use the type for the 13924/// given node type. e.g. On x86 i16 is legal, but undesirable since i16 13925/// instruction encodings are longer and some i16 instructions are slow. 13926bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const { 13927 if (!isTypeLegal(VT)) 13928 return false; 13929 if (VT != MVT::i16) 13930 return true; 13931 13932 switch (Opc) { 13933 default: 13934 return true; 13935 case ISD::LOAD: 13936 case ISD::SIGN_EXTEND: 13937 case ISD::ZERO_EXTEND: 13938 case ISD::ANY_EXTEND: 13939 case ISD::SHL: 13940 case ISD::SRL: 13941 case ISD::SUB: 13942 case ISD::ADD: 13943 case ISD::MUL: 13944 case ISD::AND: 13945 case ISD::OR: 13946 case ISD::XOR: 13947 return false; 13948 } 13949} 13950 13951/// IsDesirableToPromoteOp - This method query the target whether it is 13952/// beneficial for dag combiner to promote the specified node. If true, it 13953/// should return the desired promotion type by reference. 13954bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 13955 EVT VT = Op.getValueType(); 13956 if (VT != MVT::i16) 13957 return false; 13958 13959 bool Promote = false; 13960 bool Commute = false; 13961 switch (Op.getOpcode()) { 13962 default: break; 13963 case ISD::LOAD: { 13964 LoadSDNode *LD = cast<LoadSDNode>(Op); 13965 // If the non-extending load has a single use and it's not live out, then it 13966 // might be folded. 13967 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&& 13968 Op.hasOneUse()*/) { 13969 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 13970 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 13971 // The only case where we'd want to promote LOAD (rather then it being 13972 // promoted as an operand is when it's only use is liveout. 13973 if (UI->getOpcode() != ISD::CopyToReg) 13974 return false; 13975 } 13976 } 13977 Promote = true; 13978 break; 13979 } 13980 case ISD::SIGN_EXTEND: 13981 case ISD::ZERO_EXTEND: 13982 case ISD::ANY_EXTEND: 13983 Promote = true; 13984 break; 13985 case ISD::SHL: 13986 case ISD::SRL: { 13987 SDValue N0 = Op.getOperand(0); 13988 // Look out for (store (shl (load), x)). 13989 if (MayFoldLoad(N0) && MayFoldIntoStore(Op)) 13990 return false; 13991 Promote = true; 13992 break; 13993 } 13994 case ISD::ADD: 13995 case ISD::MUL: 13996 case ISD::AND: 13997 case ISD::OR: 13998 case ISD::XOR: 13999 Commute = true; 14000 // fallthrough 14001 case ISD::SUB: { 14002 SDValue N0 = Op.getOperand(0); 14003 SDValue N1 = Op.getOperand(1); 14004 if (!Commute && MayFoldLoad(N1)) 14005 return false; 14006 // Avoid disabling potential load folding opportunities. 14007 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op))) 14008 return false; 14009 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op))) 14010 return false; 14011 Promote = true; 14012 } 14013 } 14014 14015 PVT = MVT::i32; 14016 return Promote; 14017} 14018 14019//===----------------------------------------------------------------------===// 14020// X86 Inline Assembly Support 14021//===----------------------------------------------------------------------===// 14022 14023bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const { 14024 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 14025 14026 std::string AsmStr = IA->getAsmString(); 14027 14028 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a" 14029 SmallVector<StringRef, 4> AsmPieces; 14030 SplitString(AsmStr, AsmPieces, ";\n"); 14031 14032 switch (AsmPieces.size()) { 14033 default: return false; 14034 case 1: 14035 AsmStr = AsmPieces[0]; 14036 AsmPieces.clear(); 14037 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace. 14038 14039 // FIXME: this should verify that we are targeting a 486 or better. If not, 14040 // we will turn this bswap into something that will be lowered to logical ops 14041 // instead of emitting the bswap asm. For now, we don't support 486 or lower 14042 // so don't worry about this. 14043 // bswap $0 14044 if (AsmPieces.size() == 2 && 14045 (AsmPieces[0] == "bswap" || 14046 AsmPieces[0] == "bswapq" || 14047 AsmPieces[0] == "bswapl") && 14048 (AsmPieces[1] == "$0" || 14049 AsmPieces[1] == "${0:q}")) { 14050 // No need to check constraints, nothing other than the equivalent of 14051 // "=r,0" would be valid here. 14052 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14053 if (!Ty || Ty->getBitWidth() % 16 != 0) 14054 return false; 14055 return IntrinsicLowering::LowerToByteSwap(CI); 14056 } 14057 // rorw $$8, ${0:w} --> llvm.bswap.i16 14058 if (CI->getType()->isIntegerTy(16) && 14059 AsmPieces.size() == 3 && 14060 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") && 14061 AsmPieces[1] == "$$8," && 14062 AsmPieces[2] == "${0:w}" && 14063 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 14064 AsmPieces.clear(); 14065 const std::string &ConstraintsStr = IA->getConstraintString(); 14066 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 14067 std::sort(AsmPieces.begin(), AsmPieces.end()); 14068 if (AsmPieces.size() == 4 && 14069 AsmPieces[0] == "~{cc}" && 14070 AsmPieces[1] == "~{dirflag}" && 14071 AsmPieces[2] == "~{flags}" && 14072 AsmPieces[3] == "~{fpsr}") { 14073 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14074 if (!Ty || Ty->getBitWidth() % 16 != 0) 14075 return false; 14076 return IntrinsicLowering::LowerToByteSwap(CI); 14077 } 14078 } 14079 break; 14080 case 3: 14081 if (CI->getType()->isIntegerTy(32) && 14082 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 14083 SmallVector<StringRef, 4> Words; 14084 SplitString(AsmPieces[0], Words, " \t,"); 14085 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 14086 Words[2] == "${0:w}") { 14087 Words.clear(); 14088 SplitString(AsmPieces[1], Words, " \t,"); 14089 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" && 14090 Words[2] == "$0") { 14091 Words.clear(); 14092 SplitString(AsmPieces[2], Words, " \t,"); 14093 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 14094 Words[2] == "${0:w}") { 14095 AsmPieces.clear(); 14096 const std::string &ConstraintsStr = IA->getConstraintString(); 14097 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 14098 std::sort(AsmPieces.begin(), AsmPieces.end()); 14099 if (AsmPieces.size() == 4 && 14100 AsmPieces[0] == "~{cc}" && 14101 AsmPieces[1] == "~{dirflag}" && 14102 AsmPieces[2] == "~{flags}" && 14103 AsmPieces[3] == "~{fpsr}") { 14104 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14105 if (!Ty || Ty->getBitWidth() % 16 != 0) 14106 return false; 14107 return IntrinsicLowering::LowerToByteSwap(CI); 14108 } 14109 } 14110 } 14111 } 14112 } 14113 14114 if (CI->getType()->isIntegerTy(64)) { 14115 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 14116 if (Constraints.size() >= 2 && 14117 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" && 14118 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") { 14119 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64 14120 SmallVector<StringRef, 4> Words; 14121 SplitString(AsmPieces[0], Words, " \t"); 14122 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") { 14123 Words.clear(); 14124 SplitString(AsmPieces[1], Words, " \t"); 14125 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") { 14126 Words.clear(); 14127 SplitString(AsmPieces[2], Words, " \t,"); 14128 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" && 14129 Words[2] == "%edx") { 14130 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14131 if (!Ty || Ty->getBitWidth() % 16 != 0) 14132 return false; 14133 return IntrinsicLowering::LowerToByteSwap(CI); 14134 } 14135 } 14136 } 14137 } 14138 } 14139 break; 14140 } 14141 return false; 14142} 14143 14144 14145 14146/// getConstraintType - Given a constraint letter, return the type of 14147/// constraint it is for this target. 14148X86TargetLowering::ConstraintType 14149X86TargetLowering::getConstraintType(const std::string &Constraint) const { 14150 if (Constraint.size() == 1) { 14151 switch (Constraint[0]) { 14152 case 'R': 14153 case 'q': 14154 case 'Q': 14155 case 'f': 14156 case 't': 14157 case 'u': 14158 case 'y': 14159 case 'x': 14160 case 'Y': 14161 case 'l': 14162 return C_RegisterClass; 14163 case 'a': 14164 case 'b': 14165 case 'c': 14166 case 'd': 14167 case 'S': 14168 case 'D': 14169 case 'A': 14170 return C_Register; 14171 case 'I': 14172 case 'J': 14173 case 'K': 14174 case 'L': 14175 case 'M': 14176 case 'N': 14177 case 'G': 14178 case 'C': 14179 case 'e': 14180 case 'Z': 14181 return C_Other; 14182 default: 14183 break; 14184 } 14185 } 14186 return TargetLowering::getConstraintType(Constraint); 14187} 14188 14189/// Examine constraint type and operand type and determine a weight value. 14190/// This object must already have been set up with the operand type 14191/// and the current alternative constraint selected. 14192TargetLowering::ConstraintWeight 14193 X86TargetLowering::getSingleConstraintMatchWeight( 14194 AsmOperandInfo &info, const char *constraint) const { 14195 ConstraintWeight weight = CW_Invalid; 14196 Value *CallOperandVal = info.CallOperandVal; 14197 // If we don't have a value, we can't do a match, 14198 // but allow it at the lowest weight. 14199 if (CallOperandVal == NULL) 14200 return CW_Default; 14201 Type *type = CallOperandVal->getType(); 14202 // Look at the constraint type. 14203 switch (*constraint) { 14204 default: 14205 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14206 case 'R': 14207 case 'q': 14208 case 'Q': 14209 case 'a': 14210 case 'b': 14211 case 'c': 14212 case 'd': 14213 case 'S': 14214 case 'D': 14215 case 'A': 14216 if (CallOperandVal->getType()->isIntegerTy()) 14217 weight = CW_SpecificReg; 14218 break; 14219 case 'f': 14220 case 't': 14221 case 'u': 14222 if (type->isFloatingPointTy()) 14223 weight = CW_SpecificReg; 14224 break; 14225 case 'y': 14226 if (type->isX86_MMXTy() && Subtarget->hasMMX()) 14227 weight = CW_SpecificReg; 14228 break; 14229 case 'x': 14230 case 'Y': 14231 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM()) 14232 weight = CW_Register; 14233 break; 14234 case 'I': 14235 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) { 14236 if (C->getZExtValue() <= 31) 14237 weight = CW_Constant; 14238 } 14239 break; 14240 case 'J': 14241 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 14242 if (C->getZExtValue() <= 63) 14243 weight = CW_Constant; 14244 } 14245 break; 14246 case 'K': 14247 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 14248 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f)) 14249 weight = CW_Constant; 14250 } 14251 break; 14252 case 'L': 14253 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 14254 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff)) 14255 weight = CW_Constant; 14256 } 14257 break; 14258 case 'M': 14259 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 14260 if (C->getZExtValue() <= 3) 14261 weight = CW_Constant; 14262 } 14263 break; 14264 case 'N': 14265 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 14266 if (C->getZExtValue() <= 0xff) 14267 weight = CW_Constant; 14268 } 14269 break; 14270 case 'G': 14271 case 'C': 14272 if (dyn_cast<ConstantFP>(CallOperandVal)) { 14273 weight = CW_Constant; 14274 } 14275 break; 14276 case 'e': 14277 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 14278 if ((C->getSExtValue() >= -0x80000000LL) && 14279 (C->getSExtValue() <= 0x7fffffffLL)) 14280 weight = CW_Constant; 14281 } 14282 break; 14283 case 'Z': 14284 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 14285 if (C->getZExtValue() <= 0xffffffff) 14286 weight = CW_Constant; 14287 } 14288 break; 14289 } 14290 return weight; 14291} 14292 14293/// LowerXConstraint - try to replace an X constraint, which matches anything, 14294/// with another that has more specific requirements based on the type of the 14295/// corresponding operand. 14296const char *X86TargetLowering:: 14297LowerXConstraint(EVT ConstraintVT) const { 14298 // FP X constraints get lowered to SSE1/2 registers if available, otherwise 14299 // 'f' like normal targets. 14300 if (ConstraintVT.isFloatingPoint()) { 14301 if (Subtarget->hasXMMInt()) 14302 return "Y"; 14303 if (Subtarget->hasXMM()) 14304 return "x"; 14305 } 14306 14307 return TargetLowering::LowerXConstraint(ConstraintVT); 14308} 14309 14310/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14311/// vector. If it is invalid, don't add anything to Ops. 14312void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14313 std::string &Constraint, 14314 std::vector<SDValue>&Ops, 14315 SelectionDAG &DAG) const { 14316 SDValue Result(0, 0); 14317 14318 // Only support length 1 constraints for now. 14319 if (Constraint.length() > 1) return; 14320 14321 char ConstraintLetter = Constraint[0]; 14322 switch (ConstraintLetter) { 14323 default: break; 14324 case 'I': 14325 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 14326 if (C->getZExtValue() <= 31) { 14327 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 14328 break; 14329 } 14330 } 14331 return; 14332 case 'J': 14333 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 14334 if (C->getZExtValue() <= 63) { 14335 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 14336 break; 14337 } 14338 } 14339 return; 14340 case 'K': 14341 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 14342 if ((int8_t)C->getSExtValue() == C->getSExtValue()) { 14343 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 14344 break; 14345 } 14346 } 14347 return; 14348 case 'N': 14349 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 14350 if (C->getZExtValue() <= 255) { 14351 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 14352 break; 14353 } 14354 } 14355 return; 14356 case 'e': { 14357 // 32-bit signed value 14358 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 14359 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 14360 C->getSExtValue())) { 14361 // Widen to 64 bits here to get it sign extended. 14362 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64); 14363 break; 14364 } 14365 // FIXME gcc accepts some relocatable values here too, but only in certain 14366 // memory models; it's complicated. 14367 } 14368 return; 14369 } 14370 case 'Z': { 14371 // 32-bit unsigned value 14372 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 14373 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 14374 C->getZExtValue())) { 14375 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 14376 break; 14377 } 14378 } 14379 // FIXME gcc accepts some relocatable values here too, but only in certain 14380 // memory models; it's complicated. 14381 return; 14382 } 14383 case 'i': { 14384 // Literal immediates are always ok. 14385 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) { 14386 // Widen to 64 bits here to get it sign extended. 14387 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64); 14388 break; 14389 } 14390 14391 // In any sort of PIC mode addresses need to be computed at runtime by 14392 // adding in a register or some sort of table lookup. These can't 14393 // be used as immediates. 14394 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC()) 14395 return; 14396 14397 // If we are in non-pic codegen mode, we allow the address of a global (with 14398 // an optional displacement) to be used with 'i'. 14399 GlobalAddressSDNode *GA = 0; 14400 int64_t Offset = 0; 14401 14402 // Match either (GA), (GA+C), (GA+C1+C2), etc. 14403 while (1) { 14404 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) { 14405 Offset += GA->getOffset(); 14406 break; 14407 } else if (Op.getOpcode() == ISD::ADD) { 14408 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 14409 Offset += C->getZExtValue(); 14410 Op = Op.getOperand(0); 14411 continue; 14412 } 14413 } else if (Op.getOpcode() == ISD::SUB) { 14414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 14415 Offset += -C->getZExtValue(); 14416 Op = Op.getOperand(0); 14417 continue; 14418 } 14419 } 14420 14421 // Otherwise, this isn't something we can handle, reject it. 14422 return; 14423 } 14424 14425 const GlobalValue *GV = GA->getGlobal(); 14426 // If we require an extra load to get this address, as in PIC mode, we 14427 // can't accept it. 14428 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV, 14429 getTargetMachine()))) 14430 return; 14431 14432 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), 14433 GA->getValueType(0), Offset); 14434 break; 14435 } 14436 } 14437 14438 if (Result.getNode()) { 14439 Ops.push_back(Result); 14440 return; 14441 } 14442 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14443} 14444 14445std::pair<unsigned, const TargetRegisterClass*> 14446X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 14447 EVT VT) const { 14448 // First, see if this is a constraint that directly corresponds to an LLVM 14449 // register class. 14450 if (Constraint.size() == 1) { 14451 // GCC Constraint Letters 14452 switch (Constraint[0]) { 14453 default: break; 14454 // TODO: Slight differences here in allocation order and leaving 14455 // RIP in the class. Do they matter any more here than they do 14456 // in the normal allocation? 14457 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode. 14458 if (Subtarget->is64Bit()) { 14459 if (VT == MVT::i32 || VT == MVT::f32) 14460 return std::make_pair(0U, X86::GR32RegisterClass); 14461 else if (VT == MVT::i16) 14462 return std::make_pair(0U, X86::GR16RegisterClass); 14463 else if (VT == MVT::i8 || VT == MVT::i1) 14464 return std::make_pair(0U, X86::GR8RegisterClass); 14465 else if (VT == MVT::i64 || VT == MVT::f64) 14466 return std::make_pair(0U, X86::GR64RegisterClass); 14467 break; 14468 } 14469 // 32-bit fallthrough 14470 case 'Q': // Q_REGS 14471 if (VT == MVT::i32 || VT == MVT::f32) 14472 return std::make_pair(0U, X86::GR32_ABCDRegisterClass); 14473 else if (VT == MVT::i16) 14474 return std::make_pair(0U, X86::GR16_ABCDRegisterClass); 14475 else if (VT == MVT::i8 || VT == MVT::i1) 14476 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass); 14477 else if (VT == MVT::i64) 14478 return std::make_pair(0U, X86::GR64_ABCDRegisterClass); 14479 break; 14480 case 'r': // GENERAL_REGS 14481 case 'l': // INDEX_REGS 14482 if (VT == MVT::i8 || VT == MVT::i1) 14483 return std::make_pair(0U, X86::GR8RegisterClass); 14484 if (VT == MVT::i16) 14485 return std::make_pair(0U, X86::GR16RegisterClass); 14486 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit()) 14487 return std::make_pair(0U, X86::GR32RegisterClass); 14488 return std::make_pair(0U, X86::GR64RegisterClass); 14489 case 'R': // LEGACY_REGS 14490 if (VT == MVT::i8 || VT == MVT::i1) 14491 return std::make_pair(0U, X86::GR8_NOREXRegisterClass); 14492 if (VT == MVT::i16) 14493 return std::make_pair(0U, X86::GR16_NOREXRegisterClass); 14494 if (VT == MVT::i32 || !Subtarget->is64Bit()) 14495 return std::make_pair(0U, X86::GR32_NOREXRegisterClass); 14496 return std::make_pair(0U, X86::GR64_NOREXRegisterClass); 14497 case 'f': // FP Stack registers. 14498 // If SSE is enabled for this VT, use f80 to ensure the isel moves the 14499 // value to the correct fpstack register class. 14500 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT)) 14501 return std::make_pair(0U, X86::RFP32RegisterClass); 14502 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT)) 14503 return std::make_pair(0U, X86::RFP64RegisterClass); 14504 return std::make_pair(0U, X86::RFP80RegisterClass); 14505 case 'y': // MMX_REGS if MMX allowed. 14506 if (!Subtarget->hasMMX()) break; 14507 return std::make_pair(0U, X86::VR64RegisterClass); 14508 case 'Y': // SSE_REGS if SSE2 allowed 14509 if (!Subtarget->hasXMMInt()) break; 14510 // FALL THROUGH. 14511 case 'x': // SSE_REGS if SSE1 allowed 14512 if (!Subtarget->hasXMM()) break; 14513 14514 switch (VT.getSimpleVT().SimpleTy) { 14515 default: break; 14516 // Scalar SSE types. 14517 case MVT::f32: 14518 case MVT::i32: 14519 return std::make_pair(0U, X86::FR32RegisterClass); 14520 case MVT::f64: 14521 case MVT::i64: 14522 return std::make_pair(0U, X86::FR64RegisterClass); 14523 // Vector types. 14524 case MVT::v16i8: 14525 case MVT::v8i16: 14526 case MVT::v4i32: 14527 case MVT::v2i64: 14528 case MVT::v4f32: 14529 case MVT::v2f64: 14530 return std::make_pair(0U, X86::VR128RegisterClass); 14531 } 14532 break; 14533 } 14534 } 14535 14536 // Use the default implementation in TargetLowering to convert the register 14537 // constraint into a member of a register class. 14538 std::pair<unsigned, const TargetRegisterClass*> Res; 14539 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 14540 14541 // Not found as a standard register? 14542 if (Res.second == 0) { 14543 // Map st(0) -> st(7) -> ST0 14544 if (Constraint.size() == 7 && Constraint[0] == '{' && 14545 tolower(Constraint[1]) == 's' && 14546 tolower(Constraint[2]) == 't' && 14547 Constraint[3] == '(' && 14548 (Constraint[4] >= '0' && Constraint[4] <= '7') && 14549 Constraint[5] == ')' && 14550 Constraint[6] == '}') { 14551 14552 Res.first = X86::ST0+Constraint[4]-'0'; 14553 Res.second = X86::RFP80RegisterClass; 14554 return Res; 14555 } 14556 14557 // GCC allows "st(0)" to be called just plain "st". 14558 if (StringRef("{st}").equals_lower(Constraint)) { 14559 Res.first = X86::ST0; 14560 Res.second = X86::RFP80RegisterClass; 14561 return Res; 14562 } 14563 14564 // flags -> EFLAGS 14565 if (StringRef("{flags}").equals_lower(Constraint)) { 14566 Res.first = X86::EFLAGS; 14567 Res.second = X86::CCRRegisterClass; 14568 return Res; 14569 } 14570 14571 // 'A' means EAX + EDX. 14572 if (Constraint == "A") { 14573 Res.first = X86::EAX; 14574 Res.second = X86::GR32_ADRegisterClass; 14575 return Res; 14576 } 14577 return Res; 14578 } 14579 14580 // Otherwise, check to see if this is a register class of the wrong value 14581 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to 14582 // turn into {ax},{dx}. 14583 if (Res.second->hasType(VT)) 14584 return Res; // Correct type already, nothing to do. 14585 14586 // All of the single-register GCC register classes map their values onto 14587 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we 14588 // really want an 8-bit or 32-bit register, map to the appropriate register 14589 // class and return the appropriate register. 14590 if (Res.second == X86::GR16RegisterClass) { 14591 if (VT == MVT::i8) { 14592 unsigned DestReg = 0; 14593 switch (Res.first) { 14594 default: break; 14595 case X86::AX: DestReg = X86::AL; break; 14596 case X86::DX: DestReg = X86::DL; break; 14597 case X86::CX: DestReg = X86::CL; break; 14598 case X86::BX: DestReg = X86::BL; break; 14599 } 14600 if (DestReg) { 14601 Res.first = DestReg; 14602 Res.second = X86::GR8RegisterClass; 14603 } 14604 } else if (VT == MVT::i32) { 14605 unsigned DestReg = 0; 14606 switch (Res.first) { 14607 default: break; 14608 case X86::AX: DestReg = X86::EAX; break; 14609 case X86::DX: DestReg = X86::EDX; break; 14610 case X86::CX: DestReg = X86::ECX; break; 14611 case X86::BX: DestReg = X86::EBX; break; 14612 case X86::SI: DestReg = X86::ESI; break; 14613 case X86::DI: DestReg = X86::EDI; break; 14614 case X86::BP: DestReg = X86::EBP; break; 14615 case X86::SP: DestReg = X86::ESP; break; 14616 } 14617 if (DestReg) { 14618 Res.first = DestReg; 14619 Res.second = X86::GR32RegisterClass; 14620 } 14621 } else if (VT == MVT::i64) { 14622 unsigned DestReg = 0; 14623 switch (Res.first) { 14624 default: break; 14625 case X86::AX: DestReg = X86::RAX; break; 14626 case X86::DX: DestReg = X86::RDX; break; 14627 case X86::CX: DestReg = X86::RCX; break; 14628 case X86::BX: DestReg = X86::RBX; break; 14629 case X86::SI: DestReg = X86::RSI; break; 14630 case X86::DI: DestReg = X86::RDI; break; 14631 case X86::BP: DestReg = X86::RBP; break; 14632 case X86::SP: DestReg = X86::RSP; break; 14633 } 14634 if (DestReg) { 14635 Res.first = DestReg; 14636 Res.second = X86::GR64RegisterClass; 14637 } 14638 } 14639 } else if (Res.second == X86::FR32RegisterClass || 14640 Res.second == X86::FR64RegisterClass || 14641 Res.second == X86::VR128RegisterClass) { 14642 // Handle references to XMM physical registers that got mapped into the 14643 // wrong class. This can happen with constraints like {xmm0} where the 14644 // target independent register mapper will just pick the first match it can 14645 // find, ignoring the required type. 14646 if (VT == MVT::f32) 14647 Res.second = X86::FR32RegisterClass; 14648 else if (VT == MVT::f64) 14649 Res.second = X86::FR64RegisterClass; 14650 else if (X86::VR128RegisterClass->hasType(VT)) 14651 Res.second = X86::VR128RegisterClass; 14652 } 14653 14654 return Res; 14655} 14656