LLVM API Documentation

X86ISelLowering.cpp

Go to the documentation of this file.
00001 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the interfaces that X86 uses to lower LLVM code into a
00011 // selection DAG.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "X86.h"
00016 #include "X86InstrBuilder.h"
00017 #include "X86ISelLowering.h"
00018 #include "X86MachineFunctionInfo.h"
00019 #include "X86TargetMachine.h"
00020 #include "llvm/CallingConv.h"
00021 #include "llvm/Constants.h"
00022 #include "llvm/DerivedTypes.h"
00023 #include "llvm/GlobalVariable.h"
00024 #include "llvm/Function.h"
00025 #include "llvm/Intrinsics.h"
00026 #include "llvm/ADT/BitVector.h"
00027 #include "llvm/ADT/VectorExtras.h"
00028 #include "llvm/CodeGen/CallingConvLower.h"
00029 #include "llvm/CodeGen/MachineFrameInfo.h"
00030 #include "llvm/CodeGen/MachineFunction.h"
00031 #include "llvm/CodeGen/MachineInstrBuilder.h"
00032 #include "llvm/CodeGen/MachineModuleInfo.h"
00033 #include "llvm/CodeGen/MachineRegisterInfo.h"
00034 #include "llvm/CodeGen/PseudoSourceValue.h"
00035 #include "llvm/CodeGen/SelectionDAG.h"
00036 #include "llvm/Support/MathExtras.h"
00037 #include "llvm/Support/Debug.h"
00038 #include "llvm/Target/TargetOptions.h"
00039 #include "llvm/ADT/SmallSet.h"
00040 #include "llvm/ADT/StringExtras.h"
00041 #include "llvm/Support/CommandLine.h"
00042 using namespace llvm;
00043 
00044 static cl::opt<bool>
00045 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
00046 
00047 // Forward declarations.
00048 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
00049 
00050 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
00051   : TargetLowering(TM) {
00052   Subtarget = &TM.getSubtarget<X86Subtarget>();
00053   X86ScalarSSEf64 = Subtarget->hasSSE2();
00054   X86ScalarSSEf32 = Subtarget->hasSSE1();
00055   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
00056 
00057   bool Fast = false;
00058 
00059   RegInfo = TM.getRegisterInfo();
00060   TD = getTargetData();
00061 
00062   // Set up the TargetLowering object.
00063 
00064   // X86 is weird, it always uses i8 for shift amounts and setcc results.
00065   setShiftAmountType(MVT::i8);
00066   setBooleanContents(ZeroOrOneBooleanContent);
00067   setSchedulingPreference(SchedulingForRegPressure);
00068   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
00069   setStackPointerRegisterToSaveRestore(X86StackPtr);
00070 
00071   if (Subtarget->isTargetDarwin()) {
00072     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
00073     setUseUnderscoreSetJmp(false);
00074     setUseUnderscoreLongJmp(false);
00075   } else if (Subtarget->isTargetMingw()) {
00076     // MS runtime is weird: it exports _setjmp, but longjmp!
00077     setUseUnderscoreSetJmp(true);
00078     setUseUnderscoreLongJmp(false);
00079   } else {
00080     setUseUnderscoreSetJmp(true);
00081     setUseUnderscoreLongJmp(true);
00082   }
00083   
00084   // Set up the register classes.
00085   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
00086   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
00087   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
00088   if (Subtarget->is64Bit())
00089     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
00090 
00091   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
00092 
00093   // We don't accept any truncstore of integer registers.  
00094   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
00095   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
00096   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
00097   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
00098   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
00099   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
00100 
00101   // SETOEQ and SETUNE require checking two conditions.
00102   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
00103   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
00104   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
00105   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
00106   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
00107   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
00108 
00109   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
00110   // operation.
00111   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
00112   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
00113   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
00114 
00115   if (Subtarget->is64Bit()) {
00116     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
00117     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
00118   } else {
00119     if (X86ScalarSSEf64) {
00120       // We have an impenetrably clever algorithm for ui64->double only.
00121       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
00122 
00123       // We have faster algorithm for ui32->single only.
00124       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
00125     } else
00126       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
00127   }
00128 
00129   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
00130   // this operation.
00131   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
00132   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
00133   // SSE has no i16 to fp conversion, only i32
00134   if (X86ScalarSSEf32) {
00135     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
00136     // f32 and f64 cases are Legal, f80 case is not
00137     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
00138   } else {
00139     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
00140     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
00141   }
00142 
00143   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
00144   // are Legal, f80 is custom lowered.
00145   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
00146   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
00147 
00148   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
00149   // this operation.
00150   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
00151   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
00152 
00153   if (X86ScalarSSEf32) {
00154     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
00155     // f32 and f64 cases are Legal, f80 case is not
00156     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
00157   } else {
00158     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
00159     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
00160   }
00161 
00162   // Handle FP_TO_UINT by promoting the destination to a larger signed
00163   // conversion.
00164   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
00165   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
00166   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
00167 
00168   if (Subtarget->is64Bit()) {
00169     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
00170     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
00171   } else {
00172     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
00173       // Expand FP_TO_UINT into a select.
00174       // FIXME: We would like to use a Custom expander here eventually to do
00175       // the optimal thing for SSE vs. the default expansion in the legalizer.
00176       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
00177     else
00178       // With SSE3 we can use fisttpll to convert to a signed i64.
00179       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
00180   }
00181 
00182   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
00183   if (!X86ScalarSSEf64) {
00184     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
00185     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
00186   }
00187 
00188   // Scalar integer divide and remainder are lowered to use operations that
00189   // produce two results, to match the available instructions. This exposes
00190   // the two-result form to trivial CSE, which is able to combine x/y and x%y
00191   // into a single instruction.
00192   //
00193   // Scalar integer multiply-high is also lowered to use two-result
00194   // operations, to match the available instructions. However, plain multiply
00195   // (low) operations are left as Legal, as there are single-result
00196   // instructions for this in x86. Using the two-result multiply instructions
00197   // when both high and low results are needed must be arranged by dagcombine.
00198   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
00199   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
00200   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
00201   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
00202   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
00203   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
00204   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
00205   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
00206   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
00207   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
00208   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
00209   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
00210   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
00211   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
00212   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
00213   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
00214   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
00215   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
00216   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
00217   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
00218   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
00219   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
00220   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
00221   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
00222 
00223   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
00224   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
00225   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
00226   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
00227   if (Subtarget->is64Bit())
00228     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
00229   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
00230   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
00231   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
00232   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
00233   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
00234   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
00235   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
00236   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
00237   
00238   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
00239   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
00240   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
00241   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
00242   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
00243   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
00244   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
00245   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
00246   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
00247   if (Subtarget->is64Bit()) {
00248     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
00249     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
00250     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
00251   }
00252 
00253   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
00254   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
00255 
00256   // These should be promoted to a larger select which is supported.
00257   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
00258   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
00259   // X86 wants to expand cmov itself.
00260   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
00261   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
00262   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
00263   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
00264   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
00265   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
00266   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
00267   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
00268   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
00269   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
00270   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
00271   if (Subtarget->is64Bit()) {
00272     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
00273     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
00274   }
00275   // X86 ret instruction may pop stack.
00276   setOperationAction(ISD::RET             , MVT::Other, Custom);
00277   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
00278 
00279   // Darwin ABI issue.
00280   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
00281   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
00282   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
00283   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
00284   if (Subtarget->is64Bit())
00285     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
00286   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
00287   if (Subtarget->is64Bit()) {
00288     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
00289     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
00290     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
00291     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
00292   }
00293   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
00294   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
00295   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
00296   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
00297   if (Subtarget->is64Bit()) {
00298     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
00299     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
00300     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
00301   }
00302 
00303   if (Subtarget->hasSSE1())
00304     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
00305 
00306   if (!Subtarget->hasSSE2())
00307     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
00308 
00309   // Expand certain atomics
00310   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
00311   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
00312   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
00313   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
00314 
00315   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
00316   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
00317   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
00318   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
00319 
00320   if (!Subtarget->is64Bit()) {
00321     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
00322     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
00323     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
00324     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
00325     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
00326     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
00327     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
00328   }
00329 
00330   // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
00331   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
00332   // FIXME - use subtarget debug flags
00333   if (!Subtarget->isTargetDarwin() &&
00334       !Subtarget->isTargetELF() &&
00335       !Subtarget->isTargetCygMing()) {
00336     setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
00337     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
00338   }
00339 
00340   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
00341   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
00342   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
00343   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
00344   if (Subtarget->is64Bit()) {
00345     setExceptionPointerRegister(X86::RAX);
00346     setExceptionSelectorRegister(X86::RDX);
00347   } else {
00348     setExceptionPointerRegister(X86::EAX);
00349     setExceptionSelectorRegister(X86::EDX);
00350   }
00351   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
00352   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
00353 
00354   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
00355 
00356   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00357 
00358   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
00359   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
00360   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
00361   if (Subtarget->is64Bit()) {
00362     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
00363     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
00364   } else {
00365     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
00366     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
00367   }
00368 
00369   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
00370   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
00371   if (Subtarget->is64Bit())
00372     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
00373   if (Subtarget->isTargetCygMing())
00374     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
00375   else
00376     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
00377 
00378   if (X86ScalarSSEf64) {
00379     // f32 and f64 use SSE.
00380     // Set up the FP register classes.
00381     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
00382     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
00383 
00384     // Use ANDPD to simulate FABS.
00385     setOperationAction(ISD::FABS , MVT::f64, Custom);
00386     setOperationAction(ISD::FABS , MVT::f32, Custom);
00387 
00388     // Use XORP to simulate FNEG.
00389     setOperationAction(ISD::FNEG , MVT::f64, Custom);
00390     setOperationAction(ISD::FNEG , MVT::f32, Custom);
00391 
00392     // Use ANDPD and ORPD to simulate FCOPYSIGN.
00393     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
00394     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
00395 
00396     // We don't support sin/cos/fmod
00397     setOperationAction(ISD::FSIN , MVT::f64, Expand);
00398     setOperationAction(ISD::FCOS , MVT::f64, Expand);
00399     setOperationAction(ISD::FSIN , MVT::f32, Expand);
00400     setOperationAction(ISD::FCOS , MVT::f32, Expand);
00401 
00402     // Expand FP immediates into loads from the stack, except for the special
00403     // cases we handle.
00404     addLegalFPImmediate(APFloat(+0.0)); // xorpd
00405     addLegalFPImmediate(APFloat(+0.0f)); // xorps
00406 
00407     // Floating truncations from f80 and extensions to f80 go through memory.
00408     // If optimizing, we lie about this though and handle it in
00409     // InstructionSelectPreprocess so that dagcombine2 can hack on these.
00410     if (Fast) {
00411       setConvertAction(MVT::f32, MVT::f80, Expand);
00412       setConvertAction(MVT::f64, MVT::f80, Expand);
00413       setConvertAction(MVT::f80, MVT::f32, Expand);
00414       setConvertAction(MVT::f80, MVT::f64, Expand);
00415     }
00416   } else if (X86ScalarSSEf32) {
00417     // Use SSE for f32, x87 for f64.
00418     // Set up the FP register classes.
00419     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
00420     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
00421 
00422     // Use ANDPS to simulate FABS.
00423     setOperationAction(ISD::FABS , MVT::f32, Custom);
00424 
00425     // Use XORP to simulate FNEG.
00426     setOperationAction(ISD::FNEG , MVT::f32, Custom);
00427 
00428     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
00429 
00430     // Use ANDPS and ORPS to simulate FCOPYSIGN.
00431     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
00432     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
00433 
00434     // We don't support sin/cos/fmod
00435     setOperationAction(ISD::FSIN , MVT::f32, Expand);
00436     setOperationAction(ISD::FCOS , MVT::f32, Expand);
00437 
00438     // Special cases we handle for FP constants.
00439     addLegalFPImmediate(APFloat(+0.0f)); // xorps
00440     addLegalFPImmediate(APFloat(+0.0)); // FLD0
00441     addLegalFPImmediate(APFloat(+1.0)); // FLD1
00442     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
00443     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
00444 
00445     // SSE <-> X87 conversions go through memory.  If optimizing, we lie about
00446     // this though and handle it in InstructionSelectPreprocess so that
00447     // dagcombine2 can hack on these.
00448     if (Fast) {
00449       setConvertAction(MVT::f32, MVT::f64, Expand);
00450       setConvertAction(MVT::f32, MVT::f80, Expand);
00451       setConvertAction(MVT::f80, MVT::f32, Expand);    
00452       setConvertAction(MVT::f64, MVT::f32, Expand);
00453       // And x87->x87 truncations also.
00454       setConvertAction(MVT::f80, MVT::f64, Expand);
00455     }
00456 
00457     if (!UnsafeFPMath) {
00458       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
00459       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
00460     }
00461   } else {
00462     // f32 and f64 in x87.
00463     // Set up the FP register classes.
00464     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
00465     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
00466 
00467     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
00468     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
00469     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
00470     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
00471 
00472     // Floating truncations go through memory.  If optimizing, we lie about
00473     // this though and handle it in InstructionSelectPreprocess so that
00474     // dagcombine2 can hack on these.
00475     if (Fast) {
00476       setConvertAction(MVT::f80, MVT::f32, Expand);    
00477       setConvertAction(MVT::f64, MVT::f32, Expand);
00478       setConvertAction(MVT::f80, MVT::f64, Expand);
00479     }
00480 
00481     if (!UnsafeFPMath) {
00482       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
00483       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
00484     }
00485     addLegalFPImmediate(APFloat(+0.0)); // FLD0
00486     addLegalFPImmediate(APFloat(+1.0)); // FLD1
00487     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
00488     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
00489     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
00490     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
00491     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
00492     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
00493   }
00494 
00495   // Long double always uses X87.
00496   addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
00497   setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
00498   setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
00499   {
00500     bool ignored;
00501     APFloat TmpFlt(+0.0);
00502     TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
00503                    &ignored);
00504     addLegalFPImmediate(TmpFlt);  // FLD0
00505     TmpFlt.changeSign();
00506     addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
00507     APFloat TmpFlt2(+1.0);
00508     TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
00509                     &ignored);
00510     addLegalFPImmediate(TmpFlt2);  // FLD1
00511     TmpFlt2.changeSign();
00512     addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
00513   }
00514     
00515   if (!UnsafeFPMath) {
00516     setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
00517     setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
00518   }
00519 
00520   // Always use a library call for pow.
00521   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
00522   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
00523   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
00524 
00525   setOperationAction(ISD::FLOG, MVT::f80, Expand);
00526   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
00527   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
00528   setOperationAction(ISD::FEXP, MVT::f80, Expand);
00529   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
00530 
00531   // First set operation action for all vector types to either promote
00532   // (for widening) or expand (for scalarization). Then we will selectively
00533   // turn on ones that can be effectively codegen'd.
00534   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
00535        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
00536     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
00537     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
00538     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
00539     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
00540     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
00541     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
00542     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
00543     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
00544     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
00545     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
00546     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
00547     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
00548     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
00549     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
00550     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
00551     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
00552     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
00553     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
00554     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
00555     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
00556     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
00557     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
00558     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
00559     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
00560     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
00561     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
00562     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
00563     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
00564     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
00565     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
00566     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
00567     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
00568     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
00569     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
00570     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
00571     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
00572     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
00573     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
00574     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
00575     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
00576     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
00577     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
00578     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
00579   }
00580 
00581   if (!DisableMMX && Subtarget->hasMMX()) {
00582     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
00583     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
00584     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
00585     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
00586     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
00587 
00588     // FIXME: add MMX packed arithmetics
00589 
00590     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
00591     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
00592     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
00593     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
00594 
00595     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
00596     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
00597     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
00598     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
00599 
00600     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
00601     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
00602 
00603     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
00604     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
00605     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
00606     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
00607     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
00608     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
00609     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
00610 
00611     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
00612     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
00613     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
00614     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
00615     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
00616     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
00617     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
00618 
00619     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
00620     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
00621     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
00622     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
00623     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
00624     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
00625     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
00626 
00627     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
00628     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
00629     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
00630     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
00631     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
00632     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
00633     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
00634     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
00635     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
00636 
00637     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
00638     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
00639     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
00640     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
00641     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
00642 
00643     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
00644     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
00645     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
00646     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
00647 
00648     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
00649     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
00650     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
00651     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
00652 
00653     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
00654 
00655     setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
00656     setOperationAction(ISD::TRUNCATE,           MVT::v8i8, Expand);
00657     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
00658     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
00659     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
00660     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
00661   }
00662 
00663   if (Subtarget->hasSSE1()) {
00664     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
00665 
00666     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
00667     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
00668     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
00669     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
00670     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
00671     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
00672     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
00673     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
00674     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
00675     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
00676     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
00677     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
00678   }
00679 
00680   if (Subtarget->hasSSE2()) {
00681     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
00682     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
00683     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
00684     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
00685     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
00686 
00687     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
00688     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
00689     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
00690     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
00691     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
00692     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
00693     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
00694     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
00695     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
00696     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
00697     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
00698     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
00699     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
00700     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
00701     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
00702     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
00703 
00704     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
00705     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
00706     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
00707     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
00708 
00709     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
00710     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
00711     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
00712     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
00713     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
00714 
00715     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
00716     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
00717       MVT VT = (MVT::SimpleValueType)i;
00718       // Do not attempt to custom lower non-power-of-2 vectors
00719       if (!isPowerOf2_32(VT.getVectorNumElements()))
00720         continue;
00721       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
00722       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
00723       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
00724     }
00725     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
00726     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
00727     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
00728     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
00729     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
00730     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
00731     if (Subtarget->is64Bit()) {
00732       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
00733       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
00734     }
00735 
00736     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
00737     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
00738       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
00739       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v2i64);
00740       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
00741       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v2i64);
00742       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
00743       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v2i64);
00744       setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
00745       AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v2i64);
00746       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
00747       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
00748     }
00749 
00750     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
00751 
00752     // Custom lower v2i64 and v2f64 selects.
00753     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
00754     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
00755     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
00756     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
00757     
00758   }
00759   
00760   if (Subtarget->hasSSE41()) {
00761     // FIXME: Do we need to handle scalar-to-vector here?
00762     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
00763 
00764     // i8 and i16 vectors are custom , because the source register and source
00765     // source memory operand types are not the same width.  f32 vectors are
00766     // custom since the immediate controlling the insert encodes additional
00767     // information.
00768     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
00769     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
00770     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
00771     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
00772 
00773     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
00774     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
00775     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
00776     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
00777 
00778     if (Subtarget->is64Bit()) {
00779       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
00780       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
00781     }
00782   }
00783 
00784   if (Subtarget->hasSSE42()) {
00785     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
00786   }
00787   
00788   // We want to custom lower some of our intrinsics.
00789   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
00790 
00791   // Add/Sub/Mul with overflow operations are custom lowered.
00792   setOperationAction(ISD::SADDO, MVT::i32, Custom);
00793   setOperationAction(ISD::SADDO, MVT::i64, Custom);
00794   setOperationAction(ISD::UADDO, MVT::i32, Custom);
00795   setOperationAction(ISD::UADDO, MVT::i64, Custom);
00796   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
00797   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
00798   setOperationAction(ISD::USUBO, MVT::i32, Custom);
00799   setOperationAction(ISD::USUBO, MVT::i64, Custom);
00800   setOperationAction(ISD::SMULO, MVT::i32, Custom);
00801   setOperationAction(ISD::SMULO, MVT::i64, Custom);
00802   setOperationAction(ISD::UMULO, MVT::i32, Custom);
00803   setOperationAction(ISD::UMULO, MVT::i64, Custom);
00804 
00805   // We have target-specific dag combine patterns for the following nodes:
00806   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
00807   setTargetDAGCombine(ISD::BUILD_VECTOR);
00808   setTargetDAGCombine(ISD::SELECT);
00809   setTargetDAGCombine(ISD::SHL);
00810   setTargetDAGCombine(ISD::SRA);
00811   setTargetDAGCombine(ISD::SRL);
00812   setTargetDAGCombine(ISD::STORE);
00813 
00814   computeRegisterProperties();
00815 
00816   // FIXME: These should be based on subtarget info. Plus, the values should
00817   // be smaller when we are in optimizing for size mode.
00818   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
00819   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
00820   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
00821   allowUnalignedMemoryAccesses = true; // x86 supports it!
00822   setPrefLoopAlignment(16);
00823 }
00824 
00825 
00826 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
00827   return MVT::i8;
00828 }
00829 
00830 
00831 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
00832 /// the desired ByVal argument alignment.
00833 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
00834   if (MaxAlign == 16)
00835     return;
00836   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
00837     if (VTy->getBitWidth() == 128)
00838       MaxAlign = 16;
00839   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00840     unsigned EltAlign = 0;
00841     getMaxByValAlign(ATy->getElementType(), EltAlign);
00842     if (EltAlign > MaxAlign)
00843       MaxAlign = EltAlign;
00844   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
00845     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00846       unsigned EltAlign = 0;
00847       getMaxByValAlign(STy->getElementType(i), EltAlign);
00848       if (EltAlign > MaxAlign)
00849         MaxAlign = EltAlign;
00850       if (MaxAlign == 16)
00851         break;
00852     }
00853   }
00854   return;
00855 }
00856 
00857 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
00858 /// function arguments in the caller parameter area. For X86, aggregates
00859 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
00860 /// are at 4-byte boundaries.
00861 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
00862   if (Subtarget->is64Bit()) {
00863     // Max of 8 and alignment of type.
00864     unsigned TyAlign = TD->getABITypeAlignment(Ty);
00865     if (TyAlign > 8)
00866       return TyAlign;
00867     return 8;
00868   }
00869 
00870   unsigned Align = 4;
00871   if (Subtarget->hasSSE1())
00872     getMaxByValAlign(Ty, Align);
00873   return Align;
00874 }
00875 
00876 /// getOptimalMemOpType - Returns the target specific optimal type for load
00877 /// and store operations as a result of memset, memcpy, and memmove
00878 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
00879 /// determining it.
00880 MVT
00881 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
00882                                        bool isSrcConst, bool isSrcStr) const {
00883   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
00884   // linux.  This is because the stack realignment code can't handle certain
00885   // cases like PR2962.  This should be removed when PR2962 is fixed.
00886   if (Subtarget->getStackAlignment() >= 16) {
00887     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
00888       return MVT::v4i32;
00889     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
00890       return MVT::v4f32;
00891   }
00892   if (Subtarget->is64Bit() && Size >= 8)
00893     return MVT::i64;
00894   return MVT::i32;
00895 }
00896 
00897 
00898 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
00899 /// jumptable.
00900 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
00901                                                       SelectionDAG &DAG) const {
00902   if (usesGlobalOffsetTable())
00903     return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
00904   if (!Subtarget->isPICStyleRIPRel())
00905     return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
00906   return Table;
00907 }
00908 
00909 //===----------------------------------------------------------------------===//
00910 //               Return Value Calling Convention Implementation
00911 //===----------------------------------------------------------------------===//
00912 
00913 #include "X86GenCallingConv.inc"
00914 
00915 /// LowerRET - Lower an ISD::RET node.
00916 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
00917   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
00918   
00919   SmallVector<CCValAssign, 16> RVLocs;
00920   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
00921   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
00922   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
00923   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
00924     
00925   // If this is the first return lowered for this function, add the regs to the
00926   // liveout set for the function.
00927   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
00928     for (unsigned i = 0; i != RVLocs.size(); ++i)
00929       if (RVLocs[i].isRegLoc())
00930         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
00931   }
00932   SDValue Chain = Op.getOperand(0);
00933   
00934   // Handle tail call return.
00935   Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
00936   if (Chain.getOpcode() == X86ISD::TAILCALL) {
00937     SDValue TailCall = Chain;
00938     SDValue TargetAddress = TailCall.getOperand(1);
00939     SDValue StackAdjustment = TailCall.getOperand(2);
00940     assert(((TargetAddress.getOpcode() == ISD::Register &&
00941                (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
00942                 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
00943               TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
00944               TargetAddress.getOpcode() == ISD::TargetGlobalAddress) && 
00945              "Expecting an global address, external symbol, or register");
00946     assert(StackAdjustment.getOpcode() == ISD::Constant &&
00947            "Expecting a const value");
00948 
00949     SmallVector<SDValue,8> Operands;
00950     Operands.push_back(Chain.getOperand(0));
00951     Operands.push_back(TargetAddress);
00952     Operands.push_back(StackAdjustment);
00953     // Copy registers used by the call. Last operand is a flag so it is not
00954     // copied.
00955     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
00956       Operands.push_back(Chain.getOperand(i));
00957     }
00958     return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0], 
00959                        Operands.size());
00960   }
00961   
00962   // Regular return.
00963   SDValue Flag;
00964 
00965   SmallVector<SDValue, 6> RetOps;
00966   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
00967   // Operand #1 = Bytes To Pop
00968   RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
00969   
00970   // Copy the result values into the output registers.
00971   for (unsigned i = 0; i != RVLocs.size(); ++i) {
00972     CCValAssign &VA = RVLocs[i];
00973     assert(VA.isRegLoc() && "Can only return in registers!");
00974     SDValue ValToCopy = Op.getOperand(i*2+1);
00975     
00976     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
00977     // the RET instruction and handled by the FP Stackifier.
00978     if (RVLocs[i].getLocReg() == X86::ST0 ||
00979         RVLocs[i].getLocReg() == X86::ST1) {
00980       // If this is a copy from an xmm register to ST(0), use an FPExtend to
00981       // change the value to the FP stack register class.
00982       if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
00983         ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
00984       RetOps.push_back(ValToCopy);
00985       // Don't emit a copytoreg.
00986       continue;
00987     }
00988 
00989     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
00990     Flag = Chain.getValue(1);
00991   }
00992 
00993   // The x86-64 ABI for returning structs by value requires that we copy
00994   // the sret argument into %rax for the return. We saved the argument into
00995   // a virtual register in the entry block, so now we copy the value out
00996   // and into %rax.
00997   if (Subtarget->is64Bit() &&
00998       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
00999     MachineFunction &MF = DAG.getMachineFunction();
01000     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
01001     unsigned Reg = FuncInfo->getSRetReturnReg();
01002     if (!Reg) {
01003       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
01004       FuncInfo->setSRetReturnReg(Reg);
01005     }
01006     SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
01007 
01008     Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
01009     Flag = Chain.getValue(1);
01010   }
01011   
01012   RetOps[0] = Chain;  // Update chain.
01013 
01014   // Add the flag if we have it.
01015   if (Flag.getNode())
01016     RetOps.push_back(Flag);
01017   
01018   return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
01019 }
01020 
01021 
01022 /// LowerCallResult - Lower the result values of an ISD::CALL into the
01023 /// appropriate copies out of appropriate physical registers.  This assumes that
01024 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
01025 /// being lowered.  The returns a SDNode with the same number of values as the
01026 /// ISD::CALL.
01027 SDNode *X86TargetLowering::
01028 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall, 
01029                 unsigned CallingConv, SelectionDAG &DAG) {
01030   
01031   // Assign locations to each value returned by this call.
01032   SmallVector<CCValAssign, 16> RVLocs;
01033   bool isVarArg = TheCall->isVarArg();
01034   bool Is64Bit = Subtarget->is64Bit();
01035   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
01036   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
01037 
01038   SmallVector<SDValue, 8> ResultVals;
01039   
01040   // Copy all of the result registers out of their specified physreg.
01041   for (unsigned i = 0; i != RVLocs.size(); ++i) {
01042     MVT CopyVT = RVLocs[i].getValVT();
01043   
01044     // If this is x86-64, and we disabled SSE, we can't return FP values
01045     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 
01046         ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
01047       cerr << "SSE register return with SSE disabled\n";
01048       exit(1);
01049     }
01050 
01051     // If this is a call to a function that returns an fp value on the floating
01052     // point stack, but where we prefer to use the value in xmm registers, copy
01053     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
01054     if ((RVLocs[i].getLocReg() == X86::ST0 ||
01055          RVLocs[i].getLocReg() == X86::ST1) &&
01056         isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
01057       CopyVT = MVT::f80;
01058     }
01059     
01060     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
01061                                CopyVT, InFlag).getValue(1);
01062     SDValue Val = Chain.getValue(0);
01063     InFlag = Chain.getValue(2);
01064 
01065     if (CopyVT != RVLocs[i].getValVT()) {
01066       // Round the F80 the right size, which also moves to the appropriate xmm
01067       // register.
01068       Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
01069                         // This truncation won't change the value.
01070                         DAG.getIntPtrConstant(1));
01071     }
01072     
01073     ResultVals.push_back(Val);
01074   }
01075 
01076   // Merge everything together with a MERGE_VALUES node.
01077   ResultVals.push_back(Chain);
01078   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(), &ResultVals[0],
01079                      ResultVals.size()).getNode();
01080 }
01081 
01082 
01083 //===----------------------------------------------------------------------===//
01084 //                C & StdCall & Fast Calling Convention implementation
01085 //===----------------------------------------------------------------------===//
01086 //  StdCall calling convention seems to be standard for many Windows' API
01087 //  routines and around. It differs from C calling convention just a little:
01088 //  callee should clean up the stack, not caller. Symbols should be also
01089 //  decorated in some fancy way :) It doesn't support any vector arguments.
01090 //  For info on fast calling convention see Fast Calling Convention (tail call)
01091 //  implementation LowerX86_32FastCCCallTo.
01092 
01093 /// AddLiveIn - This helper function adds the specified physical register to the
01094 /// MachineFunction as a live in value.  It also creates a corresponding virtual
01095 /// register for it.
01096 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
01097                           const TargetRegisterClass *RC) {
01098   assert(RC->contains(PReg) && "Not the correct regclass!");
01099   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
01100   MF.getRegInfo().addLiveIn(PReg, VReg);
01101   return VReg;
01102 }
01103 
01104 /// CallIsStructReturn - Determines whether a CALL node uses struct return
01105 /// semantics.
01106 static bool CallIsStructReturn(CallSDNode *TheCall) {
01107   unsigned NumOps = TheCall->getNumArgs();
01108   if (!NumOps)
01109     return false;
01110 
01111   return TheCall->getArgFlags(0).isSRet();
01112 }
01113 
01114 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
01115 /// return semantics.
01116 static bool ArgsAreStructReturn(SDValue Op) {
01117   unsigned NumArgs = Op.getNode()->getNumValues() - 1;
01118   if (!NumArgs)
01119     return false;
01120 
01121   return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
01122 }
01123 
01124 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
01125 /// the callee to pop its own arguments. Callee pop is necessary to support tail
01126 /// calls.
01127 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
01128   if (IsVarArg)
01129     return false;
01130 
01131   switch (CallingConv) {
01132   default:
01133     return false;
01134   case CallingConv::X86_StdCall:
01135     return !Subtarget->is64Bit();
01136   case CallingConv::X86_FastCall:
01137     return !Subtarget->is64Bit();
01138   case CallingConv::Fast:
01139     return PerformTailCallOpt;
01140   }
01141 }
01142 
01143 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
01144 /// given CallingConvention value.
01145 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
01146   if (Subtarget->is64Bit()) {
01147     if (Subtarget->isTargetWin64())
01148       return CC_X86_Win64_C;
01149     else if (CC == CallingConv::Fast && PerformTailCallOpt)
01150       return CC_X86_64_TailCall;
01151     else
01152       return CC_X86_64_C;
01153   }
01154 
01155   if (CC == CallingConv::X86_FastCall)
01156     return CC_X86_32_FastCall;
01157   else if (CC == CallingConv::Fast)
01158     return CC_X86_32_FastCC;
01159   else
01160     return CC_X86_32_C;
01161 }
01162 
01163 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
01164 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
01165 NameDecorationStyle
01166 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
01167   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
01168   if (CC == CallingConv::X86_FastCall)
01169     return FastCall;
01170   else if (CC == CallingConv::X86_StdCall)
01171     return StdCall;
01172   return None;
01173 }
01174 
01175 
01176 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
01177 /// in a register before calling.
01178 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
01179   return !IsTailCall && !Is64Bit &&
01180     getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
01181     Subtarget->isPICStyleGOT();
01182 }
01183 
01184 /// CallRequiresFnAddressInReg - Check whether the call requires the function
01185 /// address to be loaded in a register.
01186 bool 
01187 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
01188   return !Is64Bit && IsTailCall &&  
01189     getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
01190     Subtarget->isPICStyleGOT();
01191 }
01192 
01193 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
01194 /// by "Src" to address "Dst" with size and alignment information specified by
01195 /// the specific parameter attribute. The copy will be passed as a byval
01196 /// function parameter.
01197 static SDValue 
01198 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
01199                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
01200   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
01201   return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
01202                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
01203 }
01204 
01205 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
01206                                               const CCValAssign &VA,
01207                                               MachineFrameInfo *MFI,
01208                                               unsigned CC,
01209                                               SDValue Root, unsigned i) {
01210   // Create the nodes corresponding to a load from this parameter slot.
01211   ISD::ArgFlagsTy Flags =
01212     cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
01213   bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
01214   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
01215 
01216   // FIXME: For now, all byval parameter objects are marked mutable. This can be
01217   // changed with more analysis.  
01218   // In case of tail call optimization mark all arguments mutable. Since they
01219   // could be overwritten by lowering of arguments in case of a tail call.
01220   int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
01221                                   VA.getLocMemOffset(), isImmutable);
01222   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
01223   if (Flags.isByVal())
01224     return FIN;
01225   return DAG.getLoad(VA.getValVT(), Root, FIN,
01226                      PseudoSourceValue::getFixedStack(FI), 0);
01227 }
01228 
01229 SDValue
01230 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
01231   MachineFunction &MF = DAG.getMachineFunction();
01232   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
01233   
01234   const Function* Fn = MF.getFunction();
01235   if (Fn->hasExternalLinkage() &&
01236       Subtarget->isTargetCygMing() &&
01237       Fn->getName() == "main")
01238     FuncInfo->setForceFramePointer(true);
01239 
01240   // Decorate the function name.
01241   FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
01242   
01243   MachineFrameInfo *MFI = MF.getFrameInfo();
01244   SDValue Root = Op.getOperand(0);
01245   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
01246   unsigned CC = MF.getFunction()->getCallingConv();
01247   bool Is64Bit = Subtarget->is64Bit();
01248   bool IsWin64 = Subtarget->isTargetWin64();
01249 
01250   assert(!(isVarArg && CC == CallingConv::Fast) &&
01251          "Var args not supported with calling convention fastcc");
01252 
01253   // Assign locations to all of the incoming arguments.
01254   SmallVector<CCValAssign, 16> ArgLocs;
01255   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
01256   CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
01257   
01258   SmallVector<SDValue, 8> ArgValues;
01259   unsigned LastVal = ~0U;
01260   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
01261     CCValAssign &VA = ArgLocs[i];
01262     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
01263     // places.
01264     assert(VA.getValNo() != LastVal &&
01265            "Don't support value assigned to multiple locs yet");
01266     LastVal = VA.getValNo();
01267     
01268     if (VA.isRegLoc()) {
01269       MVT RegVT = VA.getLocVT();
01270       TargetRegisterClass *RC = NULL;
01271       if (RegVT == MVT::i32)
01272         RC = X86::GR32RegisterClass;
01273       else if (Is64Bit && RegVT == MVT::i64)
01274         RC = X86::GR64RegisterClass;
01275       else if (RegVT == MVT::f32)
01276         RC = X86::FR32RegisterClass;
01277       else if (RegVT == MVT::f64)
01278         RC = X86::FR64RegisterClass;
01279       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
01280         RC = X86::VR128RegisterClass;
01281       else if (RegVT.isVector()) {
01282         assert(RegVT.getSizeInBits() == 64);
01283         if (!Is64Bit)
01284           RC = X86::VR64RegisterClass;     // MMX values are passed in MMXs.
01285         else {
01286           // Darwin calling convention passes MMX values in either GPRs or
01287           // XMMs in x86-64. Other targets pass them in memory.
01288           if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
01289             RC = X86::VR128RegisterClass;  // MMX values are passed in XMMs.
01290             RegVT = MVT::v2i64;
01291           } else {
01292             RC = X86::GR64RegisterClass;   // v1i64 values are passed in GPRs.
01293             RegVT = MVT::i64;
01294           }
01295         }
01296       } else {
01297         assert(0 && "Unknown argument type!");
01298       }
01299 
01300       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
01301       SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
01302       
01303       // If this is an 8 or 16-bit value, it is really passed promoted to 32
01304       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
01305       // right size.
01306       if (VA.getLocInfo() == CCValAssign::SExt)
01307         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
01308                                DAG.getValueType(VA.getValVT()));
01309       else if (VA.getLocInfo() == CCValAssign::ZExt)
01310         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
01311                                DAG.getValueType(VA.getValVT()));
01312       
01313       if (VA.getLocInfo() != CCValAssign::Full)
01314         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
01315       
01316       // Handle MMX values passed in GPRs.
01317       if (Is64Bit && RegVT != VA.getLocVT()) {
01318         if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
01319           ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
01320         else if (RC == X86::VR128RegisterClass) {
01321           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
01322                                  DAG.getConstant(0, MVT::i64));
01323           ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
01324         }
01325       }
01326       
01327       ArgValues.push_back(ArgValue);
01328     } else {
01329       assert(VA.isMemLoc());
01330       ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
01331     }
01332   }
01333 
01334   // The x86-64 ABI for returning structs by value requires that we copy
01335   // the sret argument into %rax for the return. Save the argument into
01336   // a virtual register so that we can access it from the return points.
01337   if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
01338     MachineFunction &MF = DAG.getMachineFunction();
01339     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
01340     unsigned Reg = FuncInfo->getSRetReturnReg();
01341     if (!Reg) {
01342       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
01343       FuncInfo->setSRetReturnReg(Reg);
01344     }
01345     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
01346     Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
01347   }
01348 
01349   unsigned StackSize = CCInfo.getNextStackOffset();
01350   // align stack specially for tail calls
01351   if (PerformTailCallOpt && CC == CallingConv::Fast)
01352     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
01353 
01354   // If the function takes variable number of arguments, make a frame index for
01355   // the start of the first vararg value... for expansion of llvm.va_start.
01356   if (isVarArg) {
01357     if (Is64Bit || CC != CallingConv::X86_FastCall) {
01358       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
01359     }
01360     if (Is64Bit) {
01361       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
01362 
01363       // FIXME: We should really autogenerate these arrays
01364       static const unsigned GPR64ArgRegsWin64[] = {
01365         X86::RCX, X86::RDX, X86::R8,  X86::R9
01366       };
01367       static const unsigned XMMArgRegsWin64[] = {
01368         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
01369       };
01370       static const unsigned GPR64ArgRegs64Bit[] = {
01371         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
01372       };
01373       static const unsigned XMMArgRegs64Bit[] = {
01374         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
01375         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
01376       };
01377       const unsigned *GPR64ArgRegs, *XMMArgRegs;
01378 
01379       if (IsWin64) {
01380         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
01381         GPR64ArgRegs = GPR64ArgRegsWin64;
01382         XMMArgRegs = XMMArgRegsWin64;
01383       } else {
01384         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
01385         GPR64ArgRegs = GPR64ArgRegs64Bit;
01386         XMMArgRegs = XMMArgRegs64Bit;
01387       }
01388       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
01389                                                        TotalNumIntRegs);
01390       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
01391                                                        TotalNumXMMRegs);
01392 
01393       assert((Subtarget->hasSSE1() || !NumXMMRegs) &&
01394              "SSE register cannot be used when SSE is disabled!");
01395       if (!Subtarget->hasSSE1()) {
01396         // Kernel mode asks for SSE to be disabled, so don't push them
01397         // on the stack.
01398         TotalNumXMMRegs = 0;
01399       }
01400       // For X86-64, if there are vararg parameters that are passed via
01401       // registers, then we must store them to their spots on the stack so they
01402       // may be loaded by deferencing the result of va_next.
01403       VarArgsGPOffset = NumIntRegs * 8;
01404       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
01405       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
01406                                                  TotalNumXMMRegs * 16, 16);
01407 
01408       // Store the integer parameter registers.
01409       SmallVector<SDValue, 8> MemOps;
01410       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
01411       SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
01412                                   DAG.getIntPtrConstant(VarArgsGPOffset));
01413       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
01414         unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
01415                                   X86::GR64RegisterClass);
01416         SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
01417         SDValue Store =
01418           DAG.getStore(Val.getValue(1), Val, FIN,
01419                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
01420         MemOps.push_back(Store);
01421         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
01422                           DAG.getIntPtrConstant(8));
01423       }
01424 
01425       // Now store the XMM (fp + vector) parameter registers.
01426       FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
01427                         DAG.getIntPtrConstant(VarArgsFPOffset));
01428       for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
01429         unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
01430                                   X86::VR128RegisterClass);
01431         SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
01432         SDValue Store =
01433           DAG.getStore(Val.getValue(1), Val, FIN,
01434                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
01435         MemOps.push_back(Store);
01436         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
01437                           DAG.getIntPtrConstant(16));
01438       }
01439       if (!MemOps.empty())
01440           Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
01441                              &MemOps[0], MemOps.size());
01442     }
01443   }
01444   
01445   ArgValues.push_back(Root);
01446 
01447   // Some CCs need callee pop.
01448   if (IsCalleePop(isVarArg, CC)) {
01449     BytesToPopOnReturn  = StackSize; // Callee pops everything.
01450     BytesCallerReserves = 0;
01451   } else {
01452     BytesToPopOnReturn  = 0; // Callee pops nothing.
01453     // If this is an sret function, the return should pop the hidden pointer.
01454     if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
01455       BytesToPopOnReturn = 4;  
01456     BytesCallerReserves = StackSize;
01457   }
01458 
01459   if (!Is64Bit) {
01460     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
01461     if (CC == CallingConv::X86_FastCall)
01462       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
01463   }
01464 
01465   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
01466 
01467   // Return the new list of results.
01468   return DAG.getNode(ISD::MERGE_VALUES, Op.getNode()->getVTList(),
01469                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
01470 }
01471 
01472 SDValue
01473 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
01474                                     const SDValue &StackPtr,
01475                                     const CCValAssign &VA,
01476                                     SDValue Chain,
01477                                     SDValue Arg, ISD::ArgFlagsTy Flags) {
01478   unsigned LocMemOffset = VA.getLocMemOffset();
01479   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
01480   PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
01481   if (Flags.isByVal()) {
01482     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
01483   }
01484   return DAG.getStore(Chain, Arg, PtrOff,
01485                       PseudoSourceValue::getStack(), LocMemOffset);
01486 }
01487 
01488 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
01489 /// optimization is performed and it is required.
01490 SDValue 
01491 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 
01492                                            SDValue &OutRetAddr,
01493                                            SDValue Chain, 
01494                                            bool IsTailCall, 
01495                                            bool Is64Bit, 
01496                                            int FPDiff) {
01497   if (!IsTailCall || FPDiff==0) return Chain;
01498 
01499   // Adjust the Return address stack slot.
01500   MVT VT = getPointerTy();
01501   OutRetAddr = getReturnAddressFrameIndex(DAG);
01502 
01503   // Load the "old" Return address.
01504   OutRetAddr = DAG.getLoad(VT, Chain, OutRetAddr, NULL, 0);
01505   return SDValue(OutRetAddr.getNode(), 1);
01506 }
01507 
01508 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
01509 /// optimization is performed and it is required (FPDiff!=0).
01510 static SDValue 
01511 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 
01512                          SDValue Chain, SDValue RetAddrFrIdx,
01513                          bool Is64Bit, int FPDiff) {
01514   // Store the return address to the appropriate stack slot.
01515   if (!FPDiff) return Chain;
01516   // Calculate the new stack slot for the return address.
01517   int SlotSize = Is64Bit ? 8 : 4;
01518   int NewReturnAddrFI = 
01519     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
01520   MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
01521   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
01522   Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx, 
01523                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
01524   return Chain;
01525 }
01526 
01527 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
01528   MachineFunction &MF = DAG.getMachineFunction();
01529   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
01530   SDValue Chain       = TheCall->getChain();
01531   unsigned CC         = TheCall->getCallingConv();
01532   bool isVarArg       = TheCall->isVarArg();
01533   bool IsTailCall     = TheCall->isTailCall() &&
01534                         CC == CallingConv::Fast && PerformTailCallOpt;
01535   SDValue Callee      = TheCall->getCallee();
01536   bool Is64Bit        = Subtarget->is64Bit();
01537   bool IsStructRet    = CallIsStructReturn(TheCall);
01538 
01539   assert(!(isVarArg && CC == CallingConv::Fast) &&
01540          "Var args not supported with calling convention fastcc");
01541 
01542   // Analyze operands of the call, assigning locations to each operand.
01543   SmallVector<CCValAssign, 16> ArgLocs;
01544   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
01545   CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
01546   
01547   // Get a count of how many bytes are to be pushed on the stack.
01548   unsigned NumBytes = CCInfo.getNextStackOffset();
01549   if (PerformTailCallOpt && CC == CallingConv::Fast)
01550     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
01551 
01552   int FPDiff = 0;
01553   if (IsTailCall) {
01554     // Lower arguments at fp - stackoffset + fpdiff.
01555     unsigned NumBytesCallerPushed = 
01556       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
01557     FPDiff = NumBytesCallerPushed - NumBytes;
01558 
01559     // Set the delta of movement of the returnaddr stackslot.
01560     // But only set if delta is greater than previous delta.
01561     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
01562       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
01563   }
01564 
01565   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
01566 
01567   SDValue RetAddrFrIdx;
01568   // Load return adress for tail calls.
01569   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
01570                                   FPDiff);
01571 
01572   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
01573   SmallVector<SDValue, 8> MemOpChains;
01574   SDValue StackPtr;
01575 
01576   // Walk the register/memloc assignments, inserting copies/loads.  In the case
01577   // of tail call optimization arguments are handle later.
01578   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
01579     CCValAssign &VA = ArgLocs[i];
01580     SDValue Arg = TheCall->getArg(i);
01581     ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
01582     bool isByVal = Flags.isByVal();
01583   
01584     // Promote the value if needed.
01585     switch (VA.getLocInfo()) {
01586     default: assert(0 && "Unknown loc info!");
01587     case CCValAssign::Full: break;
01588     case CCValAssign::SExt:
01589       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
01590       break;
01591     case CCValAssign::ZExt:
01592       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
01593       break;
01594     case CCValAssign::AExt:
01595       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
01596       break;
01597     }
01598     
01599     if (VA.isRegLoc()) {
01600       if (Is64Bit) {
01601         MVT RegVT = VA.getLocVT();
01602         if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
01603           switch (VA.getLocReg()) {
01604           default:
01605             break;
01606           case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
01607           case X86::R8: {
01608             // Special case: passing MMX values in GPR registers.
01609             Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
01610             break;
01611           }
01612           case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
01613           case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
01614             // Special case: passing MMX values in XMM registers.
01615             Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
01616             Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
01617             Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
01618                               DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
01619                               getMOVLMask(2, DAG));
01620             break;
01621           }
01622           }
01623       }
01624       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
01625     } else {
01626       if (!IsTailCall || (IsTailCall && isByVal)) {
01627         assert(VA.isMemLoc());
01628         if (StackPtr.getNode() == 0)
01629           StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
01630         
01631         MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
01632                                                Chain, Arg, Flags));
01633       }
01634     }
01635   }
01636   
01637   if (!MemOpChains.empty())
01638     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
01639                         &MemOpChains[0], MemOpChains.size());
01640 
01641   // Build a sequence of copy-to-reg nodes chained together with token chain
01642   // and flag operands which copy the outgoing args into registers.
01643   SDValue InFlag;
01644   // Tail call byval lowering might overwrite argument registers so in case of
01645   // tail call optimization the copies to registers are lowered later.
01646   if (!IsTailCall)
01647     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
01648       Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
01649                                InFlag);
01650       InFlag = Chain.getValue(1);
01651     }
01652 
01653   // ELF / PIC requires GOT in the EBX register before function calls via PLT
01654   // GOT pointer.  
01655   if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
01656     Chain = DAG.getCopyToReg(Chain, X86::EBX,
01657                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
01658                              InFlag);
01659     InFlag = Chain.getValue(1);
01660   }
01661   // If we are tail calling and generating PIC/GOT style code load the address
01662   // of the callee into ecx. The value in ecx is used as target of the tail
01663   // jump. This is done to circumvent the ebx/callee-saved problem for tail
01664   // calls on PIC/GOT architectures. Normally we would just put the address of
01665   // GOT into ebx and then call target@PLT. But for tail callss ebx would be
01666   // restored (since ebx is callee saved) before jumping to the target@PLT.
01667   if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
01668     // Note: The actual moving to ecx is done further down.
01669     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
01670     if (G && !G->getGlobal()->hasHiddenVisibility() &&
01671         !G->getGlobal()->hasProtectedVisibility())
01672       Callee =  LowerGlobalAddress(Callee, DAG);
01673     else if (isa<ExternalSymbolSDNode>(Callee))
01674       Callee = LowerExternalSymbol(Callee,DAG);
01675   }
01676 
01677   if (Is64Bit && isVarArg) {
01678     // From AMD64 ABI document:
01679     // For calls that may call functions that use varargs or stdargs
01680     // (prototype-less calls or calls to functions containing ellipsis (...) in
01681     // the declaration) %al is used as hidden argument to specify the number
01682     // of SSE registers used. The contents of %al do not need to match exactly
01683     // the number of registers, but must be an ubound on the number of SSE
01684     // registers used and is in the range 0 - 8 inclusive.
01685 
01686     // FIXME: Verify this on Win64
01687     // Count the number of XMM registers allocated.
01688     static const unsigned XMMArgRegs[] = {
01689       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
01690       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
01691     };
01692     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
01693     assert((Subtarget->hasSSE1() || !NumXMMRegs) 
01694            && "SSE registers cannot be used when SSE is disabled");
01695     
01696     Chain = DAG.getCopyToReg(Chain, X86::AL,
01697                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
01698     InFlag = Chain.getValue(1);
01699   }
01700 
01701 
01702   // For tail calls lower the arguments to the 'real' stack slot.
01703   if (IsTailCall) {
01704     SmallVector<SDValue, 8> MemOpChains2;
01705     SDValue FIN;
01706     int FI = 0;
01707     // Do not flag preceeding copytoreg stuff together with the following stuff.
01708     InFlag = SDValue();
01709     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
01710       CCValAssign &VA = ArgLocs[i];
01711       if (!VA.isRegLoc()) {
01712         assert(VA.isMemLoc());
01713         SDValue Arg = TheCall->getArg(i);
01714         ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
01715         // Create frame index.
01716         int32_t Offset = VA.getLocMemOffset()+FPDiff;
01717         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
01718         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
01719         FIN = DAG.getFrameIndex(FI, getPointerTy());
01720 
01721         if (Flags.isByVal()) {
01722           // Copy relative to framepointer.
01723           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
01724           if (StackPtr.getNode() == 0)
01725             StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
01726           Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
01727 
01728           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
01729                                                            Flags, DAG));
01730         } else {
01731           // Store relative to framepointer.
01732           MemOpChains2.push_back(
01733             DAG.getStore(Chain, Arg, FIN,
01734                          PseudoSourceValue::getFixedStack(FI), 0));
01735         }            
01736       }
01737     }
01738 
01739     if (!MemOpChains2.empty())
01740       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
01741                           &MemOpChains2[0], MemOpChains2.size());
01742 
01743     // Copy arguments to their registers.
01744     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
01745       Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
01746                                InFlag);
01747       InFlag = Chain.getValue(1);
01748     }
01749     InFlag =SDValue();
01750 
01751     // Store the return address to the appropriate stack slot.
01752     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
01753                                      FPDiff);
01754   }
01755 
01756   // If the callee is a GlobalAddress node (quite common, every direct call is)
01757   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
01758   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
01759     // We should use extra load for direct calls to dllimported functions in
01760     // non-JIT mode.
01761     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
01762                                         getTargetMachine(), true))
01763       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
01764                                           G->getOffset());
01765   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
01766     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
01767   } else if (IsTailCall) {
01768     unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
01769 
01770     Chain = DAG.getCopyToReg(Chain, 
01771                              DAG.getRegister(Opc, getPointerTy()), 
01772                              Callee,InFlag);
01773     Callee = DAG.getRegister(Opc, getPointerTy());
01774     // Add register as live out.
01775     DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
01776   }
01777  
01778   // Returns a chain & a flag for retval copy to use.
01779   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
01780   SmallVector<SDValue, 8> Ops;
01781 
01782   if (IsTailCall) {
01783     Ops.push_back(Chain);
01784     Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
01785     Ops.push_back(DAG.getIntPtrConstant(0, true));
01786     if (InFlag.getNode())
01787       Ops.push_back(InFlag);
01788     Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
01789     InFlag = Chain.getValue(1);
01790  
01791     // Returns a chain & a flag for retval copy to use.
01792     NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
01793     Ops.clear();
01794   }
01795   
01796   Ops.push_back(Chain);
01797   Ops.push_back(Callee);
01798 
01799   if (IsTailCall)
01800     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
01801 
01802   // Add argument registers to the end of the list so that they are known live
01803   // into the call.
01804   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
01805     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
01806                                   RegsToPass[i].second.getValueType()));
01807   
01808   // Add an implicit use GOT pointer in EBX.
01809   if (!IsTailCall && !Is64Bit &&
01810       getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
01811       Subtarget->isPICStyleGOT())
01812     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
01813 
01814   // Add an implicit use of AL for x86 vararg functions.
01815   if (Is64Bit && isVarArg)
01816     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
01817 
01818   if (InFlag.getNode())
01819     Ops.push_back(InFlag);
01820 
01821   if (IsTailCall) {
01822     assert(InFlag.getNode() && 
01823            "Flag must be set. Depend on flag being set in LowerRET");
01824     Chain = DAG.getNode(X86ISD::TAILCALL,
01825                         TheCall->getVTList(), &Ops[0], Ops.size());
01826       
01827     return SDValue(Chain.getNode(), Op.getResNo());
01828   }
01829 
01830   Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
01831   InFlag = Chain.getValue(1);
01832 
01833   // Create the CALLSEQ_END node.
01834   unsigned NumBytesForCalleeToPush;
01835   if (IsCalleePop(isVarArg, CC))
01836     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
01837   else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
01838     // If this is is a call to a struct-return function, the callee
01839     // pops the hidden struct pointer, so we have to push it back.
01840     // This is common for Darwin/X86, Linux & Mingw32 targets.
01841     NumBytesForCalleeToPush = 4;
01842   else
01843     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
01844   
01845   // Returns a flag for retval copy to use.
01846   Chain = DAG.getCALLSEQ_END(Chain,
01847                              DAG.getIntPtrConstant(NumBytes, true),
01848                              DAG.getIntPtrConstant(NumBytesForCalleeToPush,
01849                                                    true),
01850                              InFlag);
01851   InFlag = Chain.getValue(1);
01852 
01853   // Handle result values, copying them out of physregs into vregs that we
01854   // return.
01855   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
01856                  Op.getResNo());
01857 }
01858 
01859 
01860 //===----------------------------------------------------------------------===//
01861 //                Fast Calling Convention (tail call) implementation
01862 //===----------------------------------------------------------------------===//
01863 
01864 //  Like std call, callee cleans arguments, convention except that ECX is
01865 //  reserved for storing the tail called function address. Only 2 registers are
01866 //  free for argument passing (inreg). Tail call optimization is performed
01867 //  provided:
01868 //                * tailcallopt is enabled
01869 //                * caller/callee are fastcc
01870 //  On X86_64 architecture with GOT-style position independent code only local
01871 //  (within module) calls are supported at the moment.
01872 //  To keep the stack aligned according to platform abi the function
01873 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
01874 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
01875 //  If a tail called function callee has more arguments than the caller the
01876 //  caller needs to make sure that there is room to move the RETADDR to. This is
01877 //  achieved by reserving an area the size of the argument delta right after the
01878 //  original REtADDR, but before the saved framepointer or the spilled registers
01879 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
01880 //  stack layout:
01881 //    arg1
01882 //    arg2
01883 //    RETADDR
01884 //    [ new RETADDR 
01885 //      move area ]
01886 //    (possible EBP)
01887 //    ESI
01888 //    EDI
01889 //    local1 ..
01890 
01891 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
01892 /// for a 16 byte align requirement.
01893 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 
01894                                                         SelectionDAG& DAG) {
01895   MachineFunction &MF = DAG.getMachineFunction();
01896   const TargetMachine &TM = MF.getTarget();
01897   const TargetFrameInfo &TFI = *TM.getFrameInfo();
01898   unsigned StackAlignment = TFI.getStackAlignment();
01899   uint64_t AlignMask = StackAlignment - 1; 
01900   int64_t Offset = StackSize;
01901   uint64_t SlotSize = TD->getPointerSize();
01902   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
01903     // Number smaller than 12 so just add the difference.
01904     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
01905   } else {
01906     // Mask out lower bits, add stackalignment once plus the 12 bytes.
01907     Offset = ((~AlignMask) & Offset) + StackAlignment + 
01908       (StackAlignment-SlotSize);
01909   }
01910   return Offset;
01911 }
01912 
01913 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
01914 /// following the call is a return. A function is eligible if caller/callee
01915 /// calling conventions match, currently only fastcc supports tail calls, and
01916 /// the function CALL is immediatly followed by a RET.
01917 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
01918                                                       SDValue Ret,
01919                                                       SelectionDAG& DAG) const {
01920   if (!PerformTailCallOpt)
01921     return false;
01922 
01923   if (CheckTailCallReturnConstraints(TheCall, Ret)) {
01924     MachineFunction &MF = DAG.getMachineFunction();
01925     unsigned CallerCC = MF.getFunction()->getCallingConv();
01926     unsigned CalleeCC= TheCall->getCallingConv();
01927     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
01928       SDValue Callee = TheCall->getCallee();
01929       // On x86/32Bit PIC/GOT  tail calls are supported.
01930       if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
01931           !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
01932         return true;
01933 
01934       // Can only do local tail calls (in same module, hidden or protected) on
01935       // x86_64 PIC/GOT at the moment.
01936       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
01937         return G->getGlobal()->hasHiddenVisibility()
01938             || G->getGlobal()->hasProtectedVisibility();
01939     }
01940   }
01941 
01942   return false;
01943 }
01944 
01945 FastISel *
01946 X86TargetLowering::createFastISel(MachineFunction &mf,
01947                                   MachineModuleInfo *mmo,
01948                                   DwarfWriter *dw,
01949                                   DenseMap<const Value *, unsigned> &vm,
01950                                   DenseMap<const BasicBlock *,
01951                                            MachineBasicBlock *> &bm,
01952                                   DenseMap<const AllocaInst *, int> &am
01953 #ifndef NDEBUG
01954                                   , SmallSet<Instruction*, 8> &cil
01955 #endif
01956                                   ) {
01957   return X86::createFastISel(mf, mmo, dw, vm, bm, am
01958 #ifndef NDEBUG
01959                              , cil
01960 #endif
01961                              );
01962 }
01963 
01964 
01965 //===----------------------------------------------------------------------===//
01966 //                           Other Lowering Hooks
01967 //===----------------------------------------------------------------------===//
01968 
01969 
01970 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
01971   MachineFunction &MF = DAG.getMachineFunction();
01972   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
01973   int ReturnAddrIndex = FuncInfo->getRAIndex();
01974 
01975   if (ReturnAddrIndex == 0) {
01976     // Set up a frame object for the return address.
01977     uint64_t SlotSize = TD->getPointerSize();
01978     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
01979     FuncInfo->setRAIndex(ReturnAddrIndex);
01980   }
01981 
01982   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
01983 }
01984 
01985 
01986 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
01987 /// specific condition code, returning the condition code and the LHS/RHS of the
01988 /// comparison to make.
01989 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
01990                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
01991   if (!isFP) {
01992     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
01993       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
01994         // X > -1   -> X == 0, jump !sign.
01995         RHS = DAG.getConstant(0, RHS.getValueType());
01996         return X86::COND_NS;
01997       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
01998         // X < 0   -> X == 0, jump on sign.
01999         return X86::COND_S;
02000       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
02001         // X < 1   -> X <= 0
02002         RHS = DAG.getConstant(0, RHS.getValueType());
02003         return X86::COND_LE;
02004       }
02005     }
02006 
02007     switch (SetCCOpcode) {
02008     default: assert(0 && "Invalid integer condition!");
02009     case ISD::SETEQ:  return X86::COND_E;
02010     case ISD::SETGT:  return X86::COND_G;
02011     case ISD::SETGE:  return X86::COND_GE;
02012     case ISD::SETLT:  return X86::COND_L;
02013     case ISD::SETLE:  return X86::COND_LE;
02014     case ISD::SETNE:  return X86::COND_NE;
02015     case ISD::SETULT: return X86::COND_B;
02016     case ISD::SETUGT: return X86::COND_A;
02017     case ISD::SETULE: return X86::COND_BE;
02018     case ISD::SETUGE: return X86::COND_AE;
02019     }
02020   }
02021   
02022   // First determine if it is required or is profitable to flip the operands.
02023 
02024   // If LHS is a foldable load, but RHS is not, flip the condition.
02025   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
02026       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
02027     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
02028     std::swap(LHS, RHS);
02029   }
02030 
02031   switch (SetCCOpcode) {
02032   default: break;
02033   case ISD::SETOLT:
02034   case ISD::SETOLE:
02035   case ISD::SETUGT:
02036   case ISD::SETUGE:
02037     std::swap(LHS, RHS);
02038     break;
02039   }
02040 
02041   // On a floating point condition, the flags are set as follows:
02042   // ZF  PF  CF   op
02043   //  0 | 0 | 0 | X > Y
02044   //  0 | 0 | 1 | X < Y
02045   //  1 | 0 | 0 | X == Y
02046   //  1 | 1 | 1 | unordered
02047   switch (SetCCOpcode) {
02048   default: assert(0 && "Condcode should be pre-legalized away");
02049   case ISD::SETUEQ:
02050   case ISD::SETEQ:   return X86::COND_E;
02051   case ISD::SETOLT:              // flipped
02052   case ISD::SETOGT:
02053   case ISD::SETGT:   return X86::COND_A;
02054   case ISD::SETOLE:              // flipped
02055   case ISD::SETOGE:
02056   case ISD::SETGE:   return X86::COND_AE;
02057   case ISD::SETUGT:              // flipped
02058   case ISD::SETULT:
02059   case ISD::SETLT:   return X86::COND_B;
02060   case ISD::SETUGE:              // flipped
02061   case ISD::SETULE:
02062   case ISD::SETLE:   return X86::COND_BE;
02063   case ISD::SETONE:
02064   case ISD::SETNE:   return X86::COND_NE;
02065   case ISD::SETUO:   return X86::COND_P;
02066   case ISD::SETO:    return X86::COND_NP;
02067   }
02068 }
02069 
02070 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
02071 /// code. Current x86 isa includes the following FP cmov instructions:
02072 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
02073 static bool hasFPCMov(unsigned X86CC) {
02074   switch (X86CC) {
02075   default:
02076     return false;
02077   case X86::COND_B:
02078   case X86::COND_BE:
02079   case X86::COND_E:
02080   case X86::COND_P:
02081   case X86::COND_A:
02082   case X86::COND_AE:
02083   case X86::COND_NE:
02084   case X86::COND_NP:
02085     return true;
02086   }
02087 }
02088 
02089 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
02090 /// true if Op is undef or if its value falls within the specified range (L, H].
02091 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
02092   if (Op.getOpcode() == ISD::UNDEF)
02093     return true;
02094 
02095   unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
02096   return (Val >= Low && Val < Hi);
02097 }
02098 
02099 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
02100 /// true if Op is undef or if its value equal to the specified value.
02101 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
02102   if (Op.getOpcode() == ISD::UNDEF)
02103     return true;
02104   return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
02105 }
02106 
02107 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
02108 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
02109 bool X86::isPSHUFDMask(SDNode *N) {
02110   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02111 
02112   if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
02113     return false;
02114 
02115   // Check if the value doesn't reference the second vector.
02116   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
02117     SDValue Arg = N->getOperand(i);
02118     if (Arg.getOpcode() == ISD::UNDEF) continue;
02119     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02120     if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
02121       return false;
02122   }
02123 
02124   return true;
02125 }
02126 
02127 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
02128 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
02129 bool X86::isPSHUFHWMask(SDNode *N) {
02130   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02131 
02132   if (N->getNumOperands() != 8)
02133     return false;
02134 
02135   // Lower quadword copied in order.
02136   for (unsigned i = 0; i != 4; ++i) {
02137     SDValue Arg = N->getOperand(i);
02138     if (Arg.getOpcode() == ISD::UNDEF) continue;
02139     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02140     if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
02141       return false;
02142   }
02143 
02144   // Upper quadword shuffled.
02145   for (unsigned i = 4; i != 8; ++i) {
02146     SDValue Arg = N->getOperand(i);
02147     if (Arg.getOpcode() == ISD::UNDEF) continue;
02148     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02149     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02150     if (Val < 4 || Val > 7)
02151       return false;
02152   }
02153 
02154   return true;
02155 }
02156 
02157 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
02158 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
02159 bool X86::isPSHUFLWMask(SDNode *N) {
02160   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02161 
02162   if (N->getNumOperands() != 8)
02163     return false;
02164 
02165   // Upper quadword copied in order.
02166   for (unsigned i = 4; i != 8; ++i)
02167     if (!isUndefOrEqual(N->getOperand(i), i))
02168       return false;
02169 
02170   // Lower quadword shuffled.
02171   for (unsigned i = 0; i != 4; ++i)
02172     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
02173       return false;
02174 
02175   return true;
02176 }
02177 
02178 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
02179 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
02180 template<class SDOperand>
02181 static bool isSHUFPMask(SDOperand *Elems, unsigned NumElems) {
02182   if (NumElems != 2 && NumElems != 4) return false;
02183 
02184   unsigned Half = NumElems / 2;
02185   for (unsigned i = 0; i < Half; ++i)
02186     if (!isUndefOrInRange(Elems[i], 0, NumElems))
02187       return false;
02188   for (unsigned i = Half; i < NumElems; ++i)
02189     if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
02190       return false;
02191 
02192   return true;
02193 }
02194 
02195 bool X86::isSHUFPMask(SDNode *N) {
02196   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02197   return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
02198 }
02199 
02200 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
02201 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
02202 /// half elements to come from vector 1 (which would equal the dest.) and
02203 /// the upper half to come from vector 2.
02204 template<class SDOperand>
02205 static bool isCommutedSHUFP(SDOperand *Ops, unsigned NumOps) {
02206   if (NumOps != 2 && NumOps != 4) return false;
02207 
02208   unsigned Half = NumOps / 2;
02209   for (unsigned i = 0; i < Half; ++i)
02210     if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
02211       return false;
02212   for (unsigned i = Half; i < NumOps; ++i)
02213     if (!isUndefOrInRange(Ops[i], 0, NumOps))
02214       return false;
02215   return true;
02216 }
02217 
02218 static bool isCommutedSHUFP(SDNode *N) {
02219   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02220   return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
02221 }
02222 
02223 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
02224 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
02225 bool X86::isMOVHLPSMask(SDNode *N) {
02226   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02227 
02228   if (N->getNumOperands() != 4)
02229     return false;
02230 
02231   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
02232   return isUndefOrEqual(N->getOperand(0), 6) &&
02233          isUndefOrEqual(N->getOperand(1), 7) &&
02234          isUndefOrEqual(N->getOperand(2), 2) &&
02235          isUndefOrEqual(N->getOperand(3), 3);
02236 }
02237 
02238 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
02239 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
02240 /// <2, 3, 2, 3>
02241 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
02242   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02243 
02244   if (N->getNumOperands() != 4)
02245     return false;
02246 
02247   // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
02248   return isUndefOrEqual(N->getOperand(0), 2) &&
02249          isUndefOrEqual(N->getOperand(1), 3) &&
02250          isUndefOrEqual(N->getOperand(2), 2) &&
02251          isUndefOrEqual(N->getOperand(3), 3);
02252 }
02253 
02254 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
02255 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
02256 bool X86::isMOVLPMask(SDNode *N) {
02257   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02258 
02259   unsigned NumElems = N->getNumOperands();
02260   if (NumElems != 2 && NumElems != 4)
02261     return false;
02262 
02263   for (unsigned i = 0; i < NumElems/2; ++i)
02264     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
02265       return false;
02266 
02267   for (unsigned i = NumElems/2; i < NumElems; ++i)
02268     if (!isUndefOrEqual(N->getOperand(i), i))
02269       return false;
02270 
02271   return true;
02272 }
02273 
02274 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
02275 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
02276 /// and MOVLHPS.
02277 bool X86::isMOVHPMask(SDNode *N) {
02278   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02279 
02280   unsigned NumElems = N->getNumOperands();
02281   if (NumElems != 2 && NumElems != 4)
02282     return false;
02283 
02284   for (unsigned i = 0; i < NumElems/2; ++i)
02285     if (!isUndefOrEqual(N->getOperand(i), i))
02286       return false;
02287 
02288   for (unsigned i = 0; i < NumElems/2; ++i) {
02289     SDValue Arg = N->getOperand(i + NumElems/2);
02290     if (!isUndefOrEqual(Arg, i + NumElems))
02291       return false;
02292   }
02293 
02294   return true;
02295 }
02296 
02297 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
02298 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
02299 template<class SDOperand>
02300 bool static isUNPCKLMask(SDOperand *Elts, unsigned NumElts,
02301                          bool V2IsSplat = false) {
02302   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
02303     return false;
02304 
02305   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
02306     SDValue BitI  = Elts[i];
02307     SDValue BitI1 = Elts[i+1];
02308     if (!isUndefOrEqual(BitI, j))
02309       return false;
02310     if (V2IsSplat) {
02311       if (isUndefOrEqual(BitI1, NumElts))
02312         return false;
02313     } else {
02314       if (!isUndefOrEqual(BitI1, j + NumElts))
02315         return false;
02316     }
02317   }
02318 
02319   return true;
02320 }
02321 
02322 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
02323   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02324   return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
02325 }
02326 
02327 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
02328 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
02329 template<class SDOperand>
02330 bool static isUNPCKHMask(SDOperand *Elts, unsigned NumElts,
02331                          bool V2IsSplat = false) {
02332   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
02333     return false;
02334 
02335   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
02336     SDValue BitI  = Elts[i];
02337     SDValue BitI1 = Elts[i+1];
02338     if (!isUndefOrEqual(BitI, j + NumElts/2))
02339       return false;
02340     if (V2IsSplat) {
02341       if (isUndefOrEqual(BitI1, NumElts))
02342         return false;
02343     } else {
02344       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
02345         return false;
02346     }
02347   }
02348 
02349   return true;
02350 }
02351 
02352 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
02353   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02354   return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
02355 }
02356 
02357 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
02358 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
02359 /// <0, 0, 1, 1>
02360 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
02361   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02362 
02363   unsigned NumElems = N->getNumOperands();
02364   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
02365     return false;
02366 
02367   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
02368     SDValue BitI  = N->getOperand(i);
02369     SDValue BitI1 = N->getOperand(i+1);
02370 
02371     if (!isUndefOrEqual(BitI, j))
02372       return false;
02373     if (!isUndefOrEqual(BitI1, j))
02374       return false;
02375   }
02376 
02377   return true;
02378 }
02379 
02380 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
02381 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
02382 /// <2, 2, 3, 3>
02383 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
02384   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02385 
02386   unsigned NumElems = N->getNumOperands();
02387   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
02388     return false;
02389 
02390   for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
02391     SDValue BitI  = N->getOperand(i);
02392     SDValue BitI1 = N->getOperand(i + 1);
02393 
02394     if (!isUndefOrEqual(BitI, j))
02395       return false;
02396     if (!isUndefOrEqual(BitI1, j))
02397       return false;
02398   }
02399 
02400   return true;
02401 }
02402 
02403 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
02404 /// specifies a shuffle of elements that is suitable for input to MOVSS,
02405 /// MOVSD, and MOVD, i.e. setting the lowest element.
02406 template<class SDOperand>
02407 static bool isMOVLMask(SDOperand *Elts, unsigned NumElts) {
02408   if (NumElts != 2 && NumElts != 4)
02409     return false;
02410 
02411   if (!isUndefOrEqual(Elts[0], NumElts))
02412     return false;
02413 
02414   for (unsigned i = 1; i < NumElts; ++i) {
02415     if (!isUndefOrEqual(Elts[i], i))
02416       return false;
02417   }
02418 
02419   return true;
02420 }
02421 
02422 bool X86::isMOVLMask(SDNode *N) {
02423   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02424   return ::isMOVLMask(N->op_begin(), N->getNumOperands());
02425 }
02426 
02427 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
02428 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
02429 /// element of vector 2 and the other elements to come from vector 1 in order.
02430 template<class SDOperand>
02431 static bool isCommutedMOVL(SDOperand *Ops, unsigned NumOps,
02432                            bool V2IsSplat = false,
02433                            bool V2IsUndef = false) {
02434   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
02435     return false;
02436 
02437   if (!isUndefOrEqual(Ops[0], 0))
02438     return false;
02439 
02440   for (unsigned i = 1; i < NumOps; ++i) {
02441     SDValue Arg = Ops[i];
02442     if (!(isUndefOrEqual(Arg, i+NumOps) ||
02443           (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
02444           (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
02445       return false;
02446   }
02447 
02448   return true;
02449 }
02450 
02451 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
02452                            bool V2IsUndef = false) {
02453   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02454   return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
02455                         V2IsSplat, V2IsUndef);
02456 }
02457 
02458 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
02459 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
02460 bool X86::isMOVSHDUPMask(SDNode *N) {
02461   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02462 
02463   if (N->getNumOperands() != 4)
02464     return false;
02465 
02466   // Expect 1, 1, 3, 3
02467   for (unsigned i = 0; i < 2; ++i) {
02468     SDValue Arg = N->getOperand(i);
02469     if (Arg.getOpcode() == ISD::UNDEF) continue;
02470     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02471     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02472     if (Val != 1) return false;
02473   }
02474 
02475   bool HasHi = false;
02476   for (unsigned i = 2; i < 4; ++i) {
02477     SDValue Arg = N->getOperand(i);
02478     if (Arg.getOpcode() == ISD::UNDEF) continue;
02479     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02480     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02481     if (Val != 3) return false;
02482     HasHi = true;
02483   }
02484 
02485   // Don't use movshdup if it can be done with a shufps.
02486   return HasHi;
02487 }
02488 
02489 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
02490 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
02491 bool X86::isMOVSLDUPMask(SDNode *N) {
02492   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02493 
02494   if (N->getNumOperands() != 4)
02495     return false;
02496 
02497   // Expect 0, 0, 2, 2
02498   for (unsigned i = 0; i < 2; ++i) {
02499     SDValue Arg = N->getOperand(i);
02500     if (Arg.getOpcode() == ISD::UNDEF) continue;
02501     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02502     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02503     if (Val != 0) return false;
02504   }
02505 
02506   bool HasHi = false;
02507   for (unsigned i = 2; i < 4; ++i) {
02508     SDValue Arg = N->getOperand(i);
02509     if (Arg.getOpcode() == ISD::UNDEF) continue;
02510     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02511     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02512     if (Val != 2) return false;
02513     HasHi = true;
02514   }
02515 
02516   // Don't use movshdup if it can be done with a shufps.
02517   return HasHi;
02518 }
02519 
02520 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
02521 /// specifies a identity operation on the LHS or RHS.
02522 static bool isIdentityMask(SDNode *N, bool RHS = false) {
02523   unsigned NumElems = N->getNumOperands();
02524   for (unsigned i = 0; i < NumElems; ++i)
02525     if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
02526       return false;
02527   return true;
02528 }
02529 
02530 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
02531 /// a splat of a single element.
02532 static bool isSplatMask(SDNode *N) {
02533   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02534 
02535   // This is a splat operation if each element of the permute is the same, and
02536   // if the value doesn't reference the second vector.
02537   unsigned NumElems = N->getNumOperands();
02538   SDValue ElementBase;
02539   unsigned i = 0;
02540   for (; i != NumElems; ++i) {
02541     SDValue Elt = N->getOperand(i);
02542     if (isa<ConstantSDNode>(Elt)) {
02543       ElementBase = Elt;
02544       break;
02545     }
02546   }
02547 
02548   if (!ElementBase.getNode())
02549     return false;
02550 
02551   for (; i != NumElems; ++i) {
02552     SDValue Arg = N->getOperand(i);
02553     if (Arg.getOpcode() == ISD::UNDEF) continue;
02554     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02555     if (Arg != ElementBase) return false;
02556   }
02557 
02558   // Make sure it is a splat of the first vector operand.
02559   return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
02560 }
02561 
02562 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
02563 /// we want to splat.
02564 static SDValue getSplatMaskEltNo(SDNode *N) {
02565   assert(isSplatMask(N) && "Not a splat mask");
02566   unsigned NumElems = N->getNumOperands();
02567   SDValue ElementBase;
02568   unsigned i = 0;
02569   for (; i != NumElems; ++i) {
02570     SDValue Elt = N->getOperand(i);
02571     if (isa<ConstantSDNode>(Elt))
02572       return Elt;
02573   }
02574   assert(0 && " No splat value found!");
02575   return SDValue();
02576 }
02577 
02578 
02579 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
02580 /// a splat of a single element and it's a 2 or 4 element mask.
02581 bool X86::isSplatMask(SDNode *N) {
02582   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02583 
02584   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
02585   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
02586     return false;
02587   return ::isSplatMask(N);
02588 }
02589 
02590 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
02591 /// specifies a splat of zero element.
02592 bool X86::isSplatLoMask(SDNode *N) {
02593   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02594 
02595   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
02596     if (!isUndefOrEqual(N->getOperand(i), 0))
02597       return false;
02598   return true;
02599 }
02600 
02601 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
02602 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
02603 bool X86::isMOVDDUPMask(SDNode *N) {
02604   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02605 
02606   unsigned e = N->getNumOperands() / 2;
02607   for (unsigned i = 0; i < e; ++i)
02608     if (!isUndefOrEqual(N->getOperand(i), i))
02609       return false;
02610   for (unsigned i = 0; i < e; ++i)
02611     if (!isUndefOrEqual(N->getOperand(e+i), i))
02612       return false;
02613   return true;
02614 }
02615 
02616 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
02617 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
02618 /// instructions.
02619 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
02620   unsigned NumOperands = N->getNumOperands();
02621   unsigned Shift = (NumOperands == 4) ? 2 : 1;
02622   unsigned Mask = 0;
02623   for (unsigned i = 0; i < NumOperands; ++i) {
02624     unsigned Val = 0;
02625     SDValue Arg = N->getOperand(NumOperands-i-1);
02626     if (Arg.getOpcode() != ISD::UNDEF)
02627       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02628     if (Val >= NumOperands) Val -= NumOperands;
02629     Mask |= Val;
02630     if (i != NumOperands - 1)
02631       Mask <<= Shift;
02632   }
02633 
02634   return Mask;
02635 }
02636 
02637 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
02638 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
02639 /// instructions.
02640 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
02641   unsigned Mask = 0;
02642   // 8 nodes, but we only care about the last 4.
02643   for (unsigned i = 7; i >= 4; --i) {
02644     unsigned Val = 0;
02645     SDValue Arg = N->getOperand(i);
02646     if (Arg.getOpcode() != ISD::UNDEF)
02647       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02648     Mask |= (Val - 4);
02649     if (i != 4)
02650       Mask <<= 2;
02651   }
02652 
02653   return Mask;
02654 }
02655 
02656 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
02657 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
02658 /// instructions.
02659 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
02660   unsigned Mask = 0;
02661   // 8 nodes, but we only care about the first 4.
02662   for (int i = 3; i >= 0; --i) {
02663     unsigned Val = 0;
02664     SDValue Arg = N->getOperand(i);
02665     if (Arg.getOpcode() != ISD::UNDEF)
02666       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02667     Mask |= Val;
02668     if (i != 0)
02669       Mask <<= 2;
02670   }
02671 
02672   return Mask;
02673 }
02674 
02675 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
02676 /// specifies a 8 element shuffle that can be broken into a pair of
02677 /// PSHUFHW and PSHUFLW.
02678 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
02679   assert(N->getOpcode() == ISD::BUILD_VECTOR);
02680 
02681   if (N->getNumOperands() != 8)
02682     return false;
02683 
02684   // Lower quadword shuffled.
02685   for (unsigned i = 0; i != 4; ++i) {
02686     SDValue Arg = N->getOperand(i);
02687     if (Arg.getOpcode() == ISD::UNDEF) continue;
02688     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02689     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02690     if (Val >= 4)
02691       return false;
02692   }
02693 
02694   // Upper quadword shuffled.
02695   for (unsigned i = 4; i != 8; ++i) {
02696     SDValue Arg = N->getOperand(i);
02697     if (Arg.getOpcode() == ISD::UNDEF) continue;
02698     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02699     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02700     if (Val < 4 || Val > 7)
02701       return false;
02702   }
02703 
02704   return true;
02705 }
02706 
02707 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
02708 /// values in ther permute mask.
02709 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
02710                                       SDValue &V2, SDValue &Mask,
02711                                       SelectionDAG &DAG) {
02712   MVT VT = Op.getValueType();
02713   MVT MaskVT = Mask.getValueType();
02714   MVT EltVT = MaskVT.getVectorElementType();
02715   unsigned NumElems = Mask.getNumOperands();
02716   SmallVector<SDValue, 8> MaskVec;
02717 
02718   for (unsigned i = 0; i != NumElems; ++i) {
02719     SDValue Arg = Mask.getOperand(i);
02720     if (Arg.getOpcode() == ISD::UNDEF) {
02721       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
02722       continue;
02723     }
02724     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02725     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02726     if (Val < NumElems)
02727       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
02728     else
02729       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
02730   }
02731 
02732   std::swap(V1, V2);
02733   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
02734   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
02735 }
02736 
02737 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
02738 /// the two vector operands have swapped position.
02739 static
02740 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
02741   MVT MaskVT = Mask.getValueType();
02742   MVT EltVT = MaskVT.getVectorElementType();
02743   unsigned NumElems = Mask.getNumOperands();
02744   SmallVector<SDValue, 8> MaskVec;
02745   for (unsigned i = 0; i != NumElems; ++i) {
02746     SDValue Arg = Mask.getOperand(i);
02747     if (Arg.getOpcode() == ISD::UNDEF) {
02748       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
02749       continue;
02750     }
02751     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02752     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02753     if (Val < NumElems)
02754       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
02755     else
02756       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
02757   }
02758   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
02759 }
02760 
02761 
02762 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
02763 /// match movhlps. The lower half elements should come from upper half of
02764 /// V1 (and in order), and the upper half elements should come from the upper
02765 /// half of V2 (and in order).
02766 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
02767   unsigned NumElems = Mask->getNumOperands();
02768   if (NumElems != 4)
02769     return false;
02770   for (unsigned i = 0, e = 2; i != e; ++i)
02771     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
02772       return false;
02773   for (unsigned i = 2; i != 4; ++i)
02774     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
02775       return false;
02776   return true;
02777 }
02778 
02779 /// isScalarLoadToVector - Returns true if the node is a scalar load that
02780 /// is promoted to a vector. It also returns the LoadSDNode by reference if
02781 /// required.
02782 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
02783   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
02784     return false;
02785   N = N->getOperand(0).getNode();
02786   if (!ISD::isNON_EXTLoad(N))
02787     return false;
02788   if (LD)
02789     *LD = cast<LoadSDNode>(N);
02790   return true;
02791 }
02792 
02793 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
02794 /// match movlp{s|d}. The lower half elements should come from lower half of
02795 /// V1 (and in order), and the upper half elements should come from the upper
02796 /// half of V2 (and in order). And since V1 will become the source of the
02797 /// MOVLP, it must be either a vector load or a scalar load to vector.
02798 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
02799   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
02800     return false;
02801   // Is V2 is a vector load, don't do this transformation. We will try to use
02802   // load folding shufps op.
02803   if (ISD::isNON_EXTLoad(V2))
02804     return false;
02805 
02806   unsigned NumElems = Mask->getNumOperands();
02807   if (NumElems != 2 && NumElems != 4)
02808     return false;
02809   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
02810     if (!isUndefOrEqual(Mask->getOperand(i), i))
02811       return false;
02812   for (unsigned i = NumElems/2; i != NumElems; ++i)
02813     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
02814       return false;
02815   return true;
02816 }
02817 
02818 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
02819 /// all the same.
02820 static bool isSplatVector(SDNode *N) {
02821   if (N->getOpcode() != ISD::BUILD_VECTOR)
02822     return false;
02823 
02824   SDValue SplatValue = N->getOperand(0);
02825   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
02826     if (N->getOperand(i) != SplatValue)
02827       return false;
02828   return true;
02829 }
02830 
02831 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
02832 /// to an undef.
02833 static bool isUndefShuffle(SDNode *N) {
02834   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
02835     return false;
02836 
02837   SDValue V1 = N->getOperand(0);
02838   SDValue V2 = N->getOperand(1);
02839   SDValue Mask = N->getOperand(2);
02840   unsigned NumElems = Mask.getNumOperands();
02841   for (unsigned i = 0; i != NumElems; ++i) {
02842     SDValue Arg = Mask.getOperand(i);
02843     if (Arg.getOpcode() != ISD::UNDEF) {
02844       unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02845       if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
02846         return false;
02847       else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
02848         return false;
02849     }
02850   }
02851   return true;
02852 }
02853 
02854 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
02855 /// constant +0.0.
02856 static inline bool isZeroNode(SDValue Elt) {
02857   return ((isa<ConstantSDNode>(Elt) &&
02858            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
02859           (isa<ConstantFPSDNode>(Elt) &&
02860            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
02861 }
02862 
02863 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
02864 /// to an zero vector.
02865 static bool isZeroShuffle(SDNode *N) {
02866   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
02867     return false;
02868 
02869   SDValue V1 = N->getOperand(0);
02870   SDValue V2 = N->getOperand(1);
02871   SDValue Mask = N->getOperand(2);
02872   unsigned NumElems = Mask.getNumOperands();
02873   for (unsigned i = 0; i != NumElems; ++i) {
02874     SDValue Arg = Mask.getOperand(i);
02875     if (Arg.getOpcode() == ISD::UNDEF)
02876       continue;
02877     
02878     unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
02879     if (Idx < NumElems) {
02880       unsigned Opc = V1.getNode()->getOpcode();
02881       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
02882         continue;
02883       if (Opc != ISD::BUILD_VECTOR ||
02884           !isZeroNode(V1.getNode()->getOperand(Idx)))
02885         return false;
02886     } else if (Idx >= NumElems) {
02887       unsigned Opc = V2.getNode()->getOpcode();
02888       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
02889         continue;
02890       if (Opc != ISD::BUILD_VECTOR ||
02891           !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
02892         return false;
02893     }
02894   }
02895   return true;
02896 }
02897 
02898 /// getZeroVector - Returns a vector of specified type with all zero elements.
02899 ///
02900 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
02901   assert(VT.isVector() && "Expected a vector type");
02902   
02903   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
02904   // type.  This ensures they get CSE'd.
02905   SDValue Vec;
02906   if (VT.getSizeInBits() == 64) { // MMX
02907     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
02908     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
02909   } else if (HasSSE2) {  // SSE2
02910     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
02911     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
02912   } else { // SSE1
02913     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
02914     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
02915   }
02916   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
02917 }
02918 
02919 /// getOnesVector - Returns a vector of specified type with all bits set.
02920 ///
02921 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
02922   assert(VT.isVector() && "Expected a vector type");
02923   
02924   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
02925   // type.  This ensures they get CSE'd.
02926   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
02927   SDValue Vec;
02928   if (VT.getSizeInBits() == 64)  // MMX
02929     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
02930   else                                              // SSE
02931     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
02932   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
02933 }
02934 
02935 
02936 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
02937 /// that point to V2 points to its first element.
02938 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
02939   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
02940 
02941   bool Changed = false;
02942   SmallVector<SDValue, 8> MaskVec;
02943   unsigned NumElems = Mask.getNumOperands();
02944   for (unsigned i = 0; i != NumElems; ++i) {
02945     SDValue Arg = Mask.getOperand(i);
02946     if (Arg.getOpcode() != ISD::UNDEF) {
02947       unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
02948       if (Val > NumElems) {
02949         Arg = DAG.getConstant(NumElems, Arg.getValueType());
02950         Changed = true;
02951       }
02952     }
02953     MaskVec.push_back(Arg);
02954   }
02955 
02956   if (Changed)
02957     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
02958                        &MaskVec[0], MaskVec.size());
02959   return Mask;
02960 }
02961 
02962 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
02963 /// operation of specified width.
02964 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
02965   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
02966   MVT BaseVT = MaskVT.getVectorElementType();
02967 
02968   SmallVector<SDValue, 8> MaskVec;
02969   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
02970   for (unsigned i = 1; i != NumElems; ++i)
02971     MaskVec.push_back(DAG.getConstant(i, BaseVT));
02972   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
02973 }
02974 
02975 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
02976 /// of specified width.
02977 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
02978   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
02979   MVT BaseVT = MaskVT.getVectorElementType();
02980   SmallVector<SDValue, 8> MaskVec;
02981   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
02982     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
02983     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
02984   }
02985   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
02986 }
02987 
02988 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
02989 /// of specified width.
02990 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
02991   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
02992   MVT BaseVT = MaskVT.getVectorElementType();
02993   unsigned Half = NumElems/2;
02994   SmallVector<SDValue, 8> MaskVec;
02995   for (unsigned i = 0; i != Half; ++i) {
02996     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
02997     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
02998   }
02999   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
03000 }
03001 
03002 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
03003 /// element #0 of a vector with the specified index, leaving the rest of the
03004 /// elements in place.
03005 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
03006                                    SelectionDAG &DAG) {
03007   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
03008   MVT BaseVT = MaskVT.getVectorElementType();
03009   SmallVector<SDValue, 8> MaskVec;
03010   // Element #0 of the result gets the elt we are replacing.
03011   MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
03012   for (unsigned i = 1; i != NumElems; ++i)
03013     MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
03014   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
03015 }
03016 
03017 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
03018 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
03019   MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
03020   MVT VT = Op.getValueType();
03021   if (PVT == VT)
03022     return Op;
03023   SDValue V1 = Op.getOperand(0);
03024   SDValue Mask = Op.getOperand(2);
03025   unsigned MaskNumElems = Mask.getNumOperands();
03026   unsigned NumElems = MaskNumElems;
03027   // Special handling of v4f32 -> v4i32.
03028   if (VT != MVT::v4f32) {
03029     // Find which element we want to splat.
03030     SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
03031     unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
03032     // unpack elements to the correct location
03033     while (NumElems > 4) {
03034       if (EltNo < NumElems/2) {
03035         Mask = getUnpacklMask(MaskNumElems, DAG);
03036       } else {
03037         Mask = getUnpackhMask(MaskNumElems, DAG);
03038         EltNo -= NumElems/2;
03039       }
03040       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
03041       NumElems >>= 1;
03042     }
03043     SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
03044     Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
03045   }
03046 
03047   V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
03048   SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
03049                                   DAG.getNode(ISD::UNDEF, PVT), Mask);
03050   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
03051 }
03052 
03053 /// isVectorLoad - Returns true if the node is a vector load, a scalar
03054 /// load that's promoted to vector, or a load bitcasted.
03055 static bool isVectorLoad(SDValue Op) {
03056   assert(Op.getValueType().isVector() && "Expected a vector type");
03057   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
03058       Op.getOpcode() == ISD::BIT_CONVERT) {
03059     return isa<LoadSDNode>(Op.getOperand(0));
03060   }
03061   return isa<LoadSDNode>(Op);
03062 }
03063 
03064 
03065 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
03066 ///
03067 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
03068                                    SelectionDAG &DAG, bool HasSSE3) {
03069   // If we have sse3 and shuffle has more than one use or input is a load, then
03070   // use movddup. Otherwise, use movlhps.
03071   bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
03072   MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
03073   MVT VT = Op.getValueType();
03074   if (VT == PVT)
03075     return Op;
03076   unsigned NumElems = PVT.getVectorNumElements();
03077   if (NumElems == 2) {
03078     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
03079     Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
03080   } else {
03081     assert(NumElems == 4);
03082     SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
03083     SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
03084     Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst0, Cst1, Cst0, Cst1);
03085   }
03086 
03087   V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
03088   SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
03089                                 DAG.getNode(ISD::UNDEF, PVT), Mask);
03090   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
03091 }
03092 
03093 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
03094 /// vector of zero or undef vector.  This produces a shuffle where the low
03095 /// element of V2 is swizzled into the zero/undef vector, landing at element
03096 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
03097 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
03098                                              bool isZero, bool HasSSE2,
03099                                              SelectionDAG &DAG) {
03100   MVT VT = V2.getValueType();
03101   SDValue V1 = isZero
03102     ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
03103   unsigned NumElems = V2.getValueType().getVectorNumElements();
03104   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
03105   MVT EVT = MaskVT.getVectorElementType();
03106   SmallVector<SDValue, 16> MaskVec;
03107   for (unsigned i = 0; i != NumElems; ++i)
03108     if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
03109       MaskVec.push_back(DAG.getConstant(NumElems, EVT));
03110     else
03111       MaskVec.push_back(DAG.getConstant(i, EVT));
03112   SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
03113                                &MaskVec[0], MaskVec.size());
03114   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
03115 }
03116 
03117 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
03118 /// a shuffle that is zero.
03119 static
03120 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
03121                                   unsigned NumElems, bool Low,
03122                                   SelectionDAG &DAG) {
03123   unsigned NumZeros = 0;
03124   for (unsigned i = 0; i < NumElems; ++i) {
03125     unsigned Index = Low ? i : NumElems-i-1;
03126     SDValue Idx = Mask.getOperand(Index);
03127     if (Idx.getOpcode() == ISD::UNDEF) {
03128       ++NumZeros;
03129       continue;
03130     }
03131     SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
03132     if (Elt.getNode() && isZeroNode(Elt))
03133       ++NumZeros;
03134     else
03135       break;
03136   }
03137   return NumZeros;
03138 }
03139 
03140 /// isVectorShift - Returns true if the shuffle can be implemented as a
03141 /// logical left or right shift of a vector.
03142 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
03143                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
03144   unsigned NumElems = Mask.getNumOperands();
03145 
03146   isLeft = true;
03147   unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
03148   if (!NumZeros) {
03149     isLeft = false;
03150     NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
03151     if (!NumZeros)
03152       return false;
03153   }
03154 
03155   bool SeenV1 = false;
03156   bool SeenV2 = false;
03157   for (unsigned i = NumZeros; i < NumElems; ++i) {
03158     unsigned Val = isLeft ? (i - NumZeros) : i;
03159     SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
03160     if (Idx.getOpcode() == ISD::UNDEF)
03161       continue;
03162     unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
03163     if (Index < NumElems)
03164       SeenV1 = true;
03165     else {
03166       Index -= NumElems;
03167       SeenV2 = true;
03168     }
03169     if (Index != Val)
03170       return false;
03171   }
03172   if (SeenV1 && SeenV2)
03173     return false;
03174 
03175   ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
03176   ShAmt = NumZeros;
03177   return true;
03178 }
03179 
03180 
03181 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
03182 ///
03183 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
03184                                        unsigned NumNonZero, unsigned NumZero,
03185                                        SelectionDAG &DAG, TargetLowering &TLI) {
03186   if (NumNonZero > 8)
03187     return SDValue();
03188 
03189   SDValue V(0, 0);
03190   bool First = true;
03191   for (unsigned i = 0; i < 16; ++i) {
03192     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
03193     if (ThisIsNonZero && First) {
03194       if (NumZero)
03195         V = getZeroVector(MVT::v8i16, true, DAG);
03196       else
03197         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
03198       First = false;
03199     }
03200 
03201     if ((i & 1) != 0) {
03202       SDValue ThisElt(0, 0), LastElt(0, 0);
03203       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
03204       if (LastIsNonZero) {
03205         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
03206       }
03207       if (ThisIsNonZero) {
03208         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
03209         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
03210                               ThisElt, DAG.getConstant(8, MVT::i8));
03211         if (LastIsNonZero)
03212           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
03213       } else
03214         ThisElt = LastElt;
03215 
03216       if (ThisElt.getNode())
03217         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
03218                         DAG.getIntPtrConstant(i/2));
03219     }
03220   }
03221 
03222   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
03223 }
03224 
03225 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
03226 ///
03227 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
03228                                        unsigned NumNonZero, unsigned NumZero,
03229                                        SelectionDAG &DAG, TargetLowering &TLI) {
03230   if (NumNonZero > 4)
03231     return SDValue();
03232 
03233   SDValue V(0, 0);
03234   bool First = true;
03235   for (unsigned i = 0; i < 8; ++i) {
03236     bool isNonZero = (NonZeros & (1 << i)) != 0;
03237     if (isNonZero) {
03238       if (First) {
03239         if (NumZero)
03240           V = getZeroVector(MVT::v8i16, true, DAG);
03241         else
03242           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
03243         First = false;
03244       }
03245       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
03246                       DAG.getIntPtrConstant(i));
03247     }
03248   }
03249 
03250   return V;
03251 }
03252 
03253 /// getVShift - Return a vector logical shift node.
03254 ///
03255 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
03256                            unsigned NumBits, SelectionDAG &DAG,
03257                            const TargetLowering &TLI) {
03258   bool isMMX = VT.getSizeInBits() == 64;
03259   MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
03260   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
03261   SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
03262   return DAG.getNode(ISD::BIT_CONVERT, VT,
03263                      DAG.getNode(Opc, ShVT, SrcOp,
03264                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
03265 }
03266 
03267 SDValue
03268 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
03269   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
03270   if (ISD::isBuildVectorAllZeros(Op.getNode())
03271       || ISD::isBuildVectorAllOnes(Op.getNode())) {
03272     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
03273     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
03274     // eliminated on x86-32 hosts.
03275     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
03276       return Op;
03277 
03278     if (ISD::isBuildVectorAllOnes(Op.getNode()))
03279       return getOnesVector(Op.getValueType(), DAG);
03280     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
03281   }
03282 
03283   MVT VT = Op.getValueType();
03284   MVT EVT = VT.getVectorElementType();
03285   unsigned EVTBits = EVT.getSizeInBits();
03286 
03287   unsigned NumElems = Op.getNumOperands();
03288   unsigned NumZero  = 0;
03289   unsigned NumNonZero = 0;
03290   unsigned NonZeros = 0;
03291   bool IsAllConstants = true;
03292   SmallSet<SDValue, 8> Values;
03293   for (unsigned i = 0; i < NumElems; ++i) {
03294     SDValue Elt = Op.getOperand(i);
03295     if (Elt.getOpcode() == ISD::UNDEF)
03296       continue;
03297     Values.insert(Elt);
03298     if (Elt.getOpcode() != ISD::Constant &&
03299         Elt.getOpcode() != ISD::ConstantFP)
03300       IsAllConstants = false;
03301     if (isZeroNode(Elt))
03302       NumZero++;
03303     else {
03304       NonZeros |= (1 << i);
03305       NumNonZero++;
03306     }
03307   }
03308 
03309   if (NumNonZero == 0) {
03310     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
03311     return DAG.getNode(ISD::UNDEF, VT);
03312   }
03313 
03314   // Special case for single non-zero, non-undef, element.
03315   if (NumNonZero == 1 && NumElems <= 4) {
03316     unsigned Idx = CountTrailingZeros_32(NonZeros);
03317     SDValue Item = Op.getOperand(Idx);
03318     
03319     // If this is an insertion of an i64 value on x86-32, and if the top bits of
03320     // the value are obviously zero, truncate the value to i32 and do the
03321     // insertion that way.  Only do this if the value is non-constant or if the
03322     // value is a constant being inserted into element 0.  It is cheaper to do
03323     // a constant pool load than it is to do a movd + shuffle.
03324     if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
03325         (!IsAllConstants || Idx == 0)) {
03326       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
03327         // Handle MMX and SSE both.
03328         MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
03329         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
03330         
03331         // Truncate the value (which may itself be a constant) to i32, and
03332         // convert it to a vector with movd (S2V+shuffle to zero extend).
03333         Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
03334         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
03335         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
03336                                            Subtarget->hasSSE2(), DAG);
03337         
03338         // Now we have our 32-bit value zero extended in the low element of
03339         // a vector.  If Idx != 0, swizzle it into place.
03340         if (Idx != 0) {
03341           SDValue Ops[] = { 
03342             Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
03343             getSwapEltZeroMask(VecElts, Idx, DAG)
03344           };
03345           Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
03346         }
03347         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
03348       }
03349     }
03350     
03351     // If we have a constant or non-constant insertion into the low element of
03352     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
03353     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
03354     // depending on what the source datatype is.  Because we can only get here
03355     // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
03356     if (Idx == 0 &&
03357         // Don't do this for i64 values on x86-32.
03358         (EVT != MVT::i64 || Subtarget->is64Bit())) {
03359       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
03360       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
03361       return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
03362                                          Subtarget->hasSSE2(), DAG);
03363     }
03364 
03365     // Is it a vector logical left shift?
03366     if (NumElems == 2 && Idx == 1 &&
03367         isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
03368       unsigned NumBits = VT.getSizeInBits();
03369       return getVShift(true, VT,
03370                        DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
03371                        NumBits/2, DAG, *this);
03372     }
03373     
03374     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
03375       return SDValue();
03376 
03377     // Otherwise, if this is a vector with i32 or f32 elements, and the element
03378     // is a non-constant being inserted into an element other than the low one,
03379     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
03380     // movd/movss) to move this into the low element, then shuffle it into
03381     // place.
03382     if (EVTBits == 32) {
03383       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
03384       
03385       // Turn it into a shuffle of zero and zero-extended scalar to vector.
03386       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
03387                                          Subtarget->hasSSE2(), DAG);
03388       MVT MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
03389       MVT MaskEVT = MaskVT.getVectorElementType();
03390       SmallVector<SDValue, 8> MaskVec;
03391       for (unsigned i = 0; i < NumElems; i++)
03392         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
03393       SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
03394                                    &MaskVec[0], MaskVec.size());
03395       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
03396                          DAG.getNode(ISD::UNDEF, VT), Mask);
03397     }
03398   }
03399 
03400   // Splat is obviously ok. Let legalizer expand it to a shuffle.
03401   if (Values.size() == 1)
03402     return SDValue();
03403   
03404   // A vector full of immediates; various special cases are already
03405   // handled, so this is best done with a single constant-pool load.
03406   if (IsAllConstants)
03407     return SDValue();
03408 
03409   // Let legalizer expand 2-wide build_vectors.
03410   if (EVTBits == 64) {
03411     if (NumNonZero == 1) {
03412       // One half is zero or undef.
03413       unsigned Idx = CountTrailingZeros_32(NonZeros);
03414       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
03415                                  Op.getOperand(Idx));
03416       return getShuffleVectorZeroOrUndef(V2, Idx, true,
03417                                          Subtarget->hasSSE2(), DAG);
03418     }
03419     return SDValue();
03420   }
03421 
03422   // If element VT is < 32 bits, convert it to inserts into a zero vector.
03423   if (EVTBits == 8 && NumElems == 16) {
03424     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
03425                                         *this);
03426     if (V.getNode()) return V;
03427   }
03428 
03429   if (EVTBits == 16 && NumElems == 8) {
03430     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
03431                                         *this);
03432     if (V.getNode()) return V;
03433   }
03434 
03435   // If element VT is == 32 bits, turn it into a number of shuffles.
03436   SmallVector<SDValue, 8> V;
03437   V.resize(NumElems);
03438   if (NumElems == 4 && NumZero > 0) {
03439     for (unsigned i = 0; i < 4; ++i) {
03440       bool isZero = !(NonZeros & (1 << i));
03441       if (isZero)
03442         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
03443       else
03444         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
03445     }
03446 
03447     for (unsigned i = 0; i < 2; ++i) {
03448       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
03449         default: break;
03450         case 0:
03451           V[i] = V[i*2];  // Must be a zero vector.
03452           break;
03453         case 1:
03454           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
03455                              getMOVLMask(NumElems, DAG));
03456           break;
03457         case 2:
03458           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
03459                              getMOVLMask(NumElems, DAG));
03460           break;
03461         case 3:
03462           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
03463                              getUnpacklMask(NumElems, DAG));
03464           break;
03465       }
03466     }
03467 
03468     MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
03469     MVT EVT = MaskVT.getVectorElementType();
03470     SmallVector<SDValue, 8> MaskVec;
03471     bool Reverse = (NonZeros & 0x3) == 2;
03472     for (unsigned i = 0; i < 2; ++i)
03473       if (Reverse)
03474         MaskVec.push_back(DAG.getConstant(1-i, EVT));
03475       else
03476         MaskVec.push_back(DAG.getConstant(i, EVT));
03477     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
03478     for (unsigned i = 0; i < 2; ++i)
03479       if (Reverse)
03480         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
03481       else
03482         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
03483     SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
03484                                      &MaskVec[0], MaskVec.size());
03485     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
03486   }
03487 
03488   if (Values.size() > 2) {
03489     // Expand into a number of unpckl*.
03490     // e.g. for v4f32
03491     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
03492     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
03493     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
03494     SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
03495     for (unsigned i = 0; i < NumElems; ++i)
03496       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
03497     NumElems >>= 1;
03498     while (NumElems != 0) {
03499       for (unsigned i = 0; i < NumElems; ++i)
03500         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
03501                            UnpckMask);
03502       NumElems >>= 1;
03503     }
03504     return V[0];
03505   }
03506 
03507   return SDValue();
03508 }
03509 
03510 static
03511 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
03512                                  SDValue PermMask, SelectionDAG &DAG,
03513                                  TargetLowering &TLI) {
03514   SDValue NewV;
03515   MVT MaskVT = MVT::getIntVectorWithNumElements(8);
03516   MVT MaskEVT = MaskVT.getVectorElementType();
03517   MVT PtrVT = TLI.getPointerTy();
03518   SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
03519                                    PermMask.getNode()->op_end());
03520 
03521   // First record which half of which vector the low elements come from.
03522   SmallVector<unsigned, 4> LowQuad(4);
03523   for (unsigned i = 0; i < 4; ++i) {
03524     SDValue Elt = MaskElts[i];
03525     if (Elt.getOpcode() == ISD::UNDEF)
03526       continue;
03527     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
03528     int QuadIdx = EltIdx / 4;
03529     ++LowQuad[QuadIdx];
03530   }
03531 
03532   int BestLowQuad = -1;
03533   unsigned MaxQuad = 1;
03534   for (unsigned i = 0; i < 4; ++i) {
03535     if (LowQuad[i] > MaxQuad) {
03536       BestLowQuad = i;
03537       MaxQuad = LowQuad[i];
03538     }
03539   }
03540 
03541   // Record which half of which vector the high elements come from.
03542   SmallVector<unsigned, 4> HighQuad(4);
03543   for (unsigned i = 4; i < 8; ++i) {
03544     SDValue Elt = MaskElts[i];
03545     if (Elt.getOpcode() == ISD::UNDEF)
03546       continue;
03547     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
03548     int QuadIdx = EltIdx / 4;
03549     ++HighQuad[QuadIdx];
03550   }
03551 
03552   int BestHighQuad = -1;
03553   MaxQuad = 1;
03554   for (unsigned i = 0; i < 4; ++i) {
03555     if (HighQuad[i] > MaxQuad) {
03556       BestHighQuad = i;
03557       MaxQuad = HighQuad[i];
03558     }
03559   }
03560 
03561   // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
03562   if (BestLowQuad != -1 || BestHighQuad != -1) {
03563     // First sort the 4 chunks in order using shufpd.
03564     SmallVector<SDValue, 8> MaskVec;
03565 
03566     if (BestLowQuad != -1)
03567       MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
03568     else
03569       MaskVec.push_back(DAG.getConstant(0, MVT::i32));
03570 
03571     if (BestHighQuad != -1)
03572       MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
03573     else
03574       MaskVec.push_back(DAG.getConstant(1, MVT::i32));
03575 
03576     SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
03577     NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
03578                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
03579                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
03580     NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
03581 
03582     // Now sort high and low parts separately.
03583     BitVector InOrder(8);
03584     if (BestLowQuad != -1) {
03585       // Sort lower half in order using PSHUFLW.
03586       MaskVec.clear();
03587       bool AnyOutOrder = false;
03588 
03589       for (unsigned i = 0; i != 4; ++i) {
03590         SDValue Elt = MaskElts[i];
03591         if (Elt.getOpcode() == ISD::UNDEF) {
03592           MaskVec.push_back(Elt);
03593           InOrder.set(i);
03594         } else {
03595           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
03596           if (EltIdx != i)
03597             AnyOutOrder = true;
03598 
03599           MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
03600 
03601           // If this element is in the right place after this shuffle, then
03602           // remember it.
03603           if ((int)(EltIdx / 4) == BestLowQuad)
03604             InOrder.set(i);
03605         }
03606       }
03607       if (AnyOutOrder) {
03608         for (unsigned i = 4; i != 8; ++i)
03609           MaskVec.push_back(DAG.getConstant(i, MaskEVT));
03610         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
03611         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
03612       }
03613     }
03614 
03615     if (BestHighQuad != -1) {
03616       // Sort high half in order using PSHUFHW if possible.
03617       MaskVec.clear();
03618 
03619       for (unsigned i = 0; i != 4; ++i)
03620         MaskVec.push_back(DAG.getConstant(i, MaskEVT));
03621 
03622       bool AnyOutOrder = false;
03623       for (unsigned i = 4; i != 8; ++i) {
03624         SDValue Elt = MaskElts[i];
03625         if (Elt.getOpcode() == ISD::UNDEF) {
03626           MaskVec.push_back(Elt);
03627           InOrder.set(i);
03628         } else {
03629           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
03630           if (EltIdx != i)
03631             AnyOutOrder = true;
03632 
03633           MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
03634 
03635           // If this element is in the right place after this shuffle, then
03636           // remember it.
03637           if ((int)(EltIdx / 4) == BestHighQuad)
03638             InOrder.set(i);
03639         }
03640       }
03641 
03642       if (AnyOutOrder) {
03643         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
03644         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
03645       }
03646     }
03647 
03648     // The other elements are put in the right place using pextrw and pinsrw.
03649     for (unsigned i = 0; i != 8; ++i) {
03650       if (InOrder[i])
03651         continue;
03652       SDValue Elt = MaskElts[i];
03653       if (Elt.getOpcode() == ISD::UNDEF)
03654         continue;
03655       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
03656       SDValue ExtOp = (EltIdx < 8)
03657         ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
03658                       DAG.getConstant(EltIdx, PtrVT))
03659         : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
03660                       DAG.getConstant(EltIdx - 8, PtrVT));
03661       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
03662                          DAG.getConstant(i, PtrVT));
03663     }
03664 
03665     return NewV;
03666   }
03667 
03668   // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
03669   // few as possible. First, let's find out how many elements are already in the
03670   // right order.
03671   unsigned V1InOrder = 0;
03672   unsigned V1FromV1 = 0;
03673   unsigned V2InOrder = 0;
03674   unsigned V2FromV2 = 0;
03675   SmallVector<SDValue, 8> V1Elts;
03676   SmallVector<SDValue, 8> V2Elts;
03677   for (unsigned i = 0; i < 8; ++i) {
03678     SDValue Elt = MaskElts[i];
03679     if (Elt.getOpcode() == ISD::UNDEF) {
03680       V1Elts.push_back(Elt);
03681       V2Elts.push_back(Elt);
03682       ++V1InOrder;
03683       ++V2InOrder;
03684       continue;
03685     }
03686     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
03687     if (EltIdx == i) {
03688       V1Elts.push_back(Elt);
03689       V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
03690       ++V1InOrder;
03691     } else if (EltIdx == i+8) {
03692       V1Elts.push_back(Elt);
03693       V2Elts.push_back(DAG.getConstant(i, MaskEVT));
03694       ++V2InOrder;
03695     } else if (EltIdx < 8) {
03696       V1Elts.push_back(Elt);
03697       V2Elts.push_back(DAG.getConstant(EltIdx+8, MaskEVT));
03698       ++V1FromV1;
03699     } else {
03700       V1Elts.push_back(Elt);
03701       V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
03702       ++V2FromV2;
03703     }
03704   }
03705 
03706   if (V2InOrder > V1InOrder) {
03707     PermMask = CommuteVectorShuffleMask(PermMask, DAG);
03708     std::swap(V1, V2);
03709     std::swap(V1Elts, V2Elts);
03710     std::swap(V1FromV1, V2FromV2);
03711   }
03712 
03713   if ((V1FromV1 + V1InOrder) != 8) {
03714     // Some elements are from V2.
03715     if (V1FromV1) {
03716       // If there are elements that are from V1 but out of place,
03717       // then first sort them in place
03718       SmallVector<SDValue, 8> MaskVec;
03719       for (unsigned i = 0; i < 8; ++i) {
03720         SDValue Elt = V1Elts[i];
03721         if (Elt.getOpcode() == ISD::UNDEF) {
03722           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
03723           continue;
03724         }
03725         unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
03726         if (EltIdx >= 8)
03727           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
03728         else
03729           MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
03730       }
03731       SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
03732       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
03733     }
03734 
03735     NewV = V1;
03736     for (unsigned i = 0; i < 8; ++i) {
03737       SDValue Elt = V1Elts[i];
03738       if (Elt.getOpcode() == ISD::UNDEF)
03739         continue;
03740       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
03741       if (EltIdx < 8)
03742         continue;
03743       SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
03744                                     DAG.getConstant(EltIdx - 8, PtrVT));
03745       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
03746                          DAG.getConstant(i, PtrVT));
03747     }
03748     return NewV;
03749   } else {
03750     // All elements are from V1.
03751     NewV = V1;
03752     for (unsigned i = 0; i < 8; ++i) {
03753       SDValue Elt = V1Elts[i];
03754       if (Elt.getOpcode() == ISD::UNDEF)
03755         continue;
03756       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
03757       SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
03758                                     DAG.getConstant(EltIdx, PtrVT));
03759       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
03760                          DAG.getConstant(i, PtrVT));
03761     }
03762     return NewV;
03763   }
03764 }
03765 
03766 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
03767 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
03768 /// done when every pair / quad of shuffle mask elements point to elements in
03769 /// the right sequence. e.g.
03770 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
03771 static
03772 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
03773                                 MVT VT,
03774                                 SDValue PermMask, SelectionDAG &DAG,
03775                                 TargetLowering &TLI) {
03776   unsigned NumElems = PermMask.getNumOperands();
03777   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
03778   MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
03779   MVT MaskEltVT = MaskVT.getVectorElementType();
03780   MVT NewVT = MaskVT;
03781   switch (VT.getSimpleVT()) {
03782   default: assert(false && "Unexpected!");
03783   case MVT::v4f32: NewVT = MVT::v2f64; break;
03784   case MVT::v4i32: NewVT = MVT::v2i64; break;
03785   case MVT::v8i16: NewVT = MVT::v4i32; break;
03786   case MVT::v16i8: NewVT = MVT::v4i32; break;
03787   }
03788 
03789   if (NewWidth == 2) {
03790     if (VT.isInteger())
03791       NewVT = MVT::v2i64;
03792     else
03793       NewVT = MVT::v2f64;
03794   }
03795   unsigned Scale = NumElems / NewWidth;
03796   SmallVector<SDValue, 8> MaskVec;
03797   for (unsigned i = 0; i < NumElems; i += Scale) {
03798     unsigned StartIdx = ~0U;
03799     for (unsigned j = 0; j < Scale; ++j) {
03800       SDValue Elt = PermMask.getOperand(i+j);
03801       if (Elt.getOpcode() == ISD::UNDEF)
03802         continue;
03803       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
03804       if (StartIdx == ~0U)
03805         StartIdx = EltIdx - (EltIdx % Scale);
03806       if (EltIdx != StartIdx + j)
03807         return SDValue();
03808     }
03809     if (StartIdx == ~0U)
03810       MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
03811     else
03812       MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
03813   }
03814 
03815   V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
03816   V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
03817   return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
03818                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
03819                                  &MaskVec[0], MaskVec.size()));
03820 }
03821 
03822 /// getVZextMovL - Return a zero-extending vector move low node.
03823 ///
03824 static SDValue getVZextMovL(MVT VT, MVT OpVT,
03825                               SDValue SrcOp, SelectionDAG &DAG,
03826                               const X86Subtarget *Subtarget) {
03827   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
03828     LoadSDNode *LD = NULL;
03829     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
03830       LD = dyn_cast<LoadSDNode>(SrcOp);
03831     if (!LD) {
03832       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
03833       // instead.
03834       MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
03835       if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
03836           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
03837           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
03838           SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
03839         // PR2108
03840         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
03841         return DAG.getNode(ISD::BIT_CONVERT, VT,
03842                            DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
03843                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
03844                                                    SrcOp.getOperand(0)
03845                                                           .getOperand(0))));
03846       }
03847     }
03848   }
03849 
03850   return DAG.getNode(ISD::BIT_CONVERT, VT,
03851                      DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
03852                                  DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
03853 }
03854 
03855 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
03856 /// shuffles.
03857 static SDValue
03858 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
03859                           SDValue PermMask, MVT VT, SelectionDAG &DAG) {
03860   MVT MaskVT = PermMask.getValueType();
03861   MVT MaskEVT = MaskVT.getVectorElementType();
03862   SmallVector<std::pair<int, int>, 8> Locs;
03863   Locs.resize(4);
03864   SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
03865   unsigned NumHi = 0;
03866   unsigned NumLo = 0;
03867   for (unsigned i = 0; i != 4; ++i) {
03868     SDValue Elt = PermMask.getOperand(i);
03869     if (Elt.getOpcode() == ISD::UNDEF) {
03870       Locs[i] = std::make_pair(-1, -1);
03871     } else {
03872       unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
03873       assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
03874       if (Val < 4) {
03875         Locs[i] = std::make_pair(0, NumLo);
03876         Mask1[NumLo] = Elt;
03877         NumLo++;
03878       } else {
03879         Locs[i] = std::make_pair(1, NumHi);
03880         if (2+NumHi < 4)
03881           Mask1[2+NumHi] = Elt;
03882         NumHi++;
03883       }
03884     }
03885   }
03886 
03887   if (NumLo <= 2 && NumHi <= 2) {
03888     // If no more than two elements come from either vector. This can be
03889     // implemented with two shuffles. First shuffle gather the elements.
03890     // The second shuffle, which takes the first shuffle as both of its
03891     // vector operands, put the elements into the right order.
03892     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
03893                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
03894                                  &Mask1[0], Mask1.size()));
03895 
03896     SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
03897     for (unsigned i = 0; i != 4; ++i) {
03898       if (Locs[i].first == -1)
03899         continue;
03900       else {
03901         unsigned Idx = (i < 2) ? 0 : 4;
03902         Idx += Locs[i].first * 2 + Locs[i].second;
03903         Mask2[i] = DAG.getConstant(Idx, MaskEVT);
03904       }
03905     }
03906 
03907     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
03908                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
03909                                    &Mask2[0], Mask2.size()));
03910   } else if (NumLo == 3 || NumHi == 3) {
03911     // Otherwise, we must have three elements from one vector, call it X, and
03912     // one element from the other, call it Y.  First, use a shufps to build an
03913     // intermediate vector with the one element from Y and the element from X
03914     // that will be in the same half in the final destination (the indexes don't
03915     // matter). Then, use a shufps to build the final vector, taking the half
03916     // containing the element from Y from the intermediate, and the other half
03917     // from X.
03918     if (NumHi == 3) {
03919       // Normalize it so the 3 elements come from V1.
03920       PermMask = CommuteVectorShuffleMask(PermMask, DAG);
03921       std::swap(V1, V2);
03922     }
03923 
03924     // Find the element from V2.
03925     unsigned HiIndex;
03926     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
03927       SDValue Elt = PermMask.getOperand(HiIndex);
03928       if (Elt.getOpcode() == ISD::UNDEF)
03929         continue;
03930       unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
03931       if (Val >= 4)
03932         break;
03933     }
03934 
03935     Mask1[0] = PermMask.getOperand(HiIndex);
03936     Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
03937     Mask1[2] = PermMask.getOperand(HiIndex^1);
03938     Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
03939     V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
03940                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
03941 
03942     if (HiIndex >= 2) {
03943       Mask1[0] = PermMask.getOperand(0);
03944       Mask1[1] = PermMask.getOperand(1);
03945       Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
03946       Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
03947       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
03948                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
03949     } else {
03950       Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
03951       Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
03952       Mask1[2] = PermMask.getOperand(2);
03953       Mask1[3] = PermMask.getOperand(3);
03954       if (Mask1[2].getOpcode() != ISD::UNDEF)
03955         Mask1[2] =
03956           DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
03957                           MaskEVT);
03958       if (Mask1[3].getOpcode() != ISD::UNDEF)
03959         Mask1[3] =
03960           DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
03961                           MaskEVT);
03962       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
03963                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
03964     }
03965   }
03966 
03967   // Break it into (shuffle shuffle_hi, shuffle_lo).
03968   Locs.clear();
03969   SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
03970   SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
03971   SmallVector<SDValue,8> *MaskPtr = &LoMask;
03972   unsigned MaskIdx = 0;
03973   unsigned LoIdx = 0;
03974   unsigned HiIdx = 2;
03975   for (unsigned i = 0; i != 4; ++i) {
03976     if (i == 2) {
03977       MaskPtr = &HiMask;
03978       MaskIdx = 1;
03979       LoIdx = 0;
03980       HiIdx = 2;
03981     }
03982     SDValue Elt = PermMask.getOperand(i);
03983     if (Elt.getOpcode() == ISD::UNDEF) {
03984       Locs[i] = std::make_pair(-1, -1);
03985     } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
03986       Locs[i] = std::make_pair(MaskIdx, LoIdx);
03987       (*MaskPtr)[LoIdx] = Elt;
03988       LoIdx++;
03989     } else {
03990       Locs[i] = std::make_pair(MaskIdx, HiIdx);
03991       (*MaskPtr)[HiIdx] = Elt;
03992       HiIdx++;
03993     }
03994   }
03995 
03996   SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
03997                                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
03998                                                 &LoMask[0], LoMask.size()));
03999   SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
04000                                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
04001                                                 &HiMask[0], HiMask.size()));
04002   SmallVector<SDValue, 8> MaskOps;
04003   for (unsigned i = 0; i != 4; ++i) {
04004     if (Locs[i].first == -1) {
04005       MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
04006     } else {
04007       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
04008       MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
04009     }
04010   }
04011   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
04012                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
04013                                  &MaskOps[0], MaskOps.size()));
04014 }
04015 
04016 SDValue
04017 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
04018   SDValue V1 = Op.getOperand(0);
04019   SDValue V2 = Op.getOperand(1);
04020   SDValue PermMask = Op.getOperand(2);
04021   MVT VT = Op.getValueType();
04022   unsigned NumElems = PermMask.getNumOperands();
04023   bool isMMX = VT.getSizeInBits() == 64;
04024   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
04025   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
04026   bool V1IsSplat = false;
04027   bool V2IsSplat = false;
04028 
04029   if (isUndefShuffle(Op.getNode()))
04030     return DAG.getNode(ISD::UNDEF, VT);
04031 
04032   if (isZeroShuffle(Op.getNode()))
04033     return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
04034 
04035   if (isIdentityMask(PermMask.getNode()))
04036     return V1;
04037   else if (isIdentityMask(PermMask.getNode(), true))
04038     return V2;
04039 
04040   // Canonicalize movddup shuffles.
04041   if (V2IsUndef && Subtarget->hasSSE2() &&
04042       VT.getSizeInBits() == 128 &&
04043       X86::isMOVDDUPMask(PermMask.getNode()))
04044     return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
04045 
04046   if (isSplatMask(PermMask.getNode())) {
04047     if (isMMX || NumElems < 4) return Op;
04048     // Promote it to a v4{if}32 splat.
04049     return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
04050   }
04051 
04052   // If the shuffle can be profitably rewritten as a narrower shuffle, then
04053   // do it!
04054   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
04055     SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
04056     if (NewOp.getNode())
04057       return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
04058   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
04059     // FIXME: Figure out a cleaner way to do this.
04060     // Try to make use of movq to zero out the top part.
04061     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
04062       SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
04063                                                  DAG, *this);
04064       if (NewOp.getNode()) {
04065         SDValue NewV1 = NewOp.getOperand(0);
04066         SDValue NewV2 = NewOp.getOperand(1);
04067         SDValue NewMask = NewOp.getOperand(2);
04068         if (isCommutedMOVL(NewMask.getNode(), true, false)) {
04069           NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
04070           return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
04071         }
04072       }
04073     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
04074       SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
04075                                                 DAG, *this);
04076       if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
04077         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
04078                              DAG, Subtarget);
04079     }
04080   }
04081 
04082   // Check if this can be converted into a logical shift.
04083   bool isLeft = false;
04084   unsigned ShAmt = 0;
04085   SDValue ShVal;
04086   bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
04087   if (isShift && ShVal.hasOneUse()) {
04088     // If the shifted value has multiple uses, it may be cheaper to use 
04089     // v_set0 + movlhps or movhlps, etc.
04090     MVT EVT = VT.getVectorElementType();
04091     ShAmt *= EVT.getSizeInBits();
04092     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
04093   }
04094 
04095   if (X86::isMOVLMask(PermMask.getNode())) {
04096     if (V1IsUndef)
04097       return V2;
04098     if (ISD::isBuildVectorAllZeros(V1.getNode()))
04099       return getVZextMovL(VT, VT, V2, DAG, Subtarget);
04100     if (!isMMX)
04101       return Op;
04102   }
04103 
04104   if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
04105                  X86::isMOVSLDUPMask(PermMask.getNode()) ||
04106                  X86::isMOVHLPSMask(PermMask.getNode()) ||
04107                  X86::isMOVHPMask(PermMask.getNode()) ||
04108                  X86::isMOVLPMask(PermMask.getNode())))
04109     return Op;
04110 
04111   if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
04112       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
04113     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
04114 
04115   if (isShift) {
04116     // No better options. Use a vshl / vsrl.
04117     MVT EVT = VT.getVectorElementType();
04118     ShAmt *= EVT.getSizeInBits();
04119     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
04120   }
04121 
04122   bool Commuted = false;
04123   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
04124   // 1,1,1,1 -> v8i16 though.
04125   V1IsSplat = isSplatVector(V1.getNode());
04126   V2IsSplat = isSplatVector(V2.getNode());
04127   
04128   // Canonicalize the splat or undef, if present, to be on the RHS.
04129   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
04130     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
04131     std::swap(V1IsSplat, V2IsSplat);
04132     std::swap(V1IsUndef, V2IsUndef);
04133     Commuted = true;
04134   }
04135 
04136   // FIXME: Figure out a cleaner way to do this.
04137   if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
04138     if (V2IsUndef) return V1;
04139     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
04140     if (V2IsSplat) {
04141       // V2 is a splat, so the mask may be malformed. That is, it may point
04142       // to any V2 element. The instruction selectior won't like this. Get
04143       // a corrected mask and commute to form a proper MOVS{S|D}.
04144       SDValue NewMask = getMOVLMask(NumElems, DAG);
04145       if (NewMask.getNode() != PermMask.getNode())
04146         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
04147     }
04148     return Op;
04149   }
04150 
04151   if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
04152       X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
04153       X86::isUNPCKLMask(PermMask.getNode()) ||
04154       X86::isUNPCKHMask(PermMask.getNode()))
04155     return Op;
04156 
04157   if (V2IsSplat) {
04158     // Normalize mask so all entries that point to V2 points to its first
04159     // element then try to match unpck{h|l} again. If match, return a
04160     // new vector_shuffle with the corrected mask.
04161     SDValue NewMask = NormalizeMask(PermMask, DAG);
04162     if (NewMask.getNode() != PermMask.getNode()) {
04163       if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
04164         SDValue NewMask = getUnpacklMask(NumElems, DAG);
04165         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
04166       } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
04167         SDValue NewMask = getUnpackhMask(NumElems, DAG);
04168         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
04169       }
04170     }
04171   }
04172 
04173   // Normalize the node to match x86 shuffle ops if needed
04174   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
04175       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
04176 
04177   if (Commuted) {
04178     // Commute is back and try unpck* again.
04179     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
04180     if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
04181         X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
04182         X86::isUNPCKLMask(PermMask.getNode()) ||
04183         X86::isUNPCKHMask(PermMask.getNode()))
04184       return Op;
04185   }
04186 
04187   // Try PSHUF* first, then SHUFP*.
04188   // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
04189   // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
04190   if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
04191     if (V2.getOpcode() != ISD::UNDEF)
04192       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
04193                          DAG.getNode(ISD::UNDEF, VT), PermMask);
04194     return Op;
04195   }
04196 
04197   if (!isMMX) {
04198     if (Subtarget->hasSSE2() &&
04199         (X86::isPSHUFDMask(PermMask.getNode()) ||
04200          X86::isPSHUFHWMask(PermMask.getNode()) ||
04201          X86::isPSHUFLWMask(PermMask.getNode()))) {
04202       MVT RVT = VT;
04203       if (VT == MVT::v4f32) {
04204         RVT = MVT::v4i32;
04205         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
04206                          DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
04207                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
04208       } else if (V2.getOpcode() != ISD::UNDEF)
04209         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
04210                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
04211       if (RVT != VT)
04212         Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
04213       return Op;
04214     }
04215 
04216     // Binary or unary shufps.
04217     if (X86::isSHUFPMask(PermMask.getNode()) ||
04218         (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
04219       return Op;
04220   }
04221 
04222   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
04223   if (VT == MVT::v8i16) {
04224     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
04225     if (NewOp.getNode())
04226       return NewOp;
04227   }
04228 
04229   // Handle all 4 wide cases with a number of shuffles except for MMX.
04230   if (NumElems == 4 && !isMMX)
04231     return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
04232 
04233   return SDValue();
04234 }
04235 
04236 SDValue
04237 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
04238                                                 SelectionDAG &DAG) {
04239   MVT VT = Op.getValueType();
04240   if (VT.getSizeInBits() == 8) {
04241     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
04242                                     Op.getOperand(0), Op.getOperand(1));
04243     SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
04244                                     DAG.getValueType(VT));
04245     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
04246   } else if (VT.getSizeInBits() == 16) {
04247     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
04248     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
04249     if (Idx == 0)
04250       return DAG.getNode(ISD::TRUNCATE, MVT::i16,
04251                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
04252                                      DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32,
04253                                                  Op.getOperand(0)),
04254                                      Op.getOperand(1)));
04255     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
04256                                     Op.getOperand(0), Op.getOperand(1));
04257     SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
04258                                     DAG.getValueType(VT));
04259     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
04260   } else if (VT == MVT::f32) {
04261     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
04262     // the result back to FR32 register. It's only worth matching if the
04263     // result has a single use which is a store or a bitcast to i32.  And in
04264     // the case of a store, it's not worth it if the index is a constant 0,
04265     // because a MOVSSmr can be used instead, which is smaller and faster.
04266     if (!Op.hasOneUse())
04267       return SDValue();
04268     SDNode *User = *Op.getNode()->use_begin();
04269     if ((User->getOpcode() != ISD::STORE ||
04270          (isa<ConstantSDNode>(Op.getOperand(1)) &&
04271           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
04272         (User->getOpcode() != ISD::BIT_CONVERT ||
04273          User->getValueType(0) != MVT::i32))
04274       return SDValue();
04275     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
04276                     DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
04277                                     Op.getOperand(1));
04278     return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
04279   } else if (VT == MVT::i32) {
04280     // ExtractPS works with constant index.
04281     if (isa<ConstantSDNode>(Op.getOperand(1)))
04282       return Op;
04283   }
04284   return SDValue();
04285 }
04286 
04287 
04288 SDValue
04289 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
04290   if (!isa<ConstantSDNode>(Op.getOperand(1)))
04291     return SDValue();
04292 
04293   if (Subtarget->hasSSE41()) {
04294     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
04295     if (Res.getNode())
04296       return Res;
04297   }
04298 
04299   MVT VT = Op.getValueType();
04300   // TODO: handle v16i8.
04301   if (VT.getSizeInBits() == 16) {
04302     SDValue Vec = Op.getOperand(0);
04303     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
04304     if (Idx == 0)
04305       return DAG.getNode(ISD::TRUNCATE, MVT::i16,
04306                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
04307                                  DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
04308                                      Op.getOperand(1)));
04309     // Transform it so it match pextrw which produces a 32-bit result.
04310     MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
04311     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
04312                                     Op.getOperand(0), Op.getOperand(1));
04313     SDValue Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
04314                                     DAG.getValueType(VT));
04315     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
04316   } else if (VT.getSizeInBits() == 32) {
04317     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
04318     if (Idx == 0)
04319       return Op;
04320     // SHUFPS the element to the lowest double word, then movss.
04321     MVT MaskVT = MVT::getIntVectorWithNumElements(4);
04322     SmallVector<SDValue, 8> IdxVec;
04323     IdxVec.
04324       push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
04325     IdxVec.
04326       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
04327     IdxVec.
04328       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
04329     IdxVec.
04330       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
04331     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
04332                                  &IdxVec[0], IdxVec.size());
04333     SDValue Vec = Op.getOperand(0);
04334     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
04335                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
04336     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
04337                        DAG.getIntPtrConstant(0));
04338   } else if (VT.getSizeInBits() == 64) {
04339     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
04340     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
04341     //        to match extract_elt for f64.
04342     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
04343     if (Idx == 0)
04344       return Op;
04345 
04346     // UNPCKHPD the element to the lowest double word, then movsd.
04347     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
04348     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
04349     MVT MaskVT = MVT::getIntVectorWithNumElements(2);
04350     SmallVector<SDValue, 8> IdxVec;
04351     IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
04352     IdxVec.
04353       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
04354     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
04355                                  &IdxVec[0], IdxVec.size());
04356     SDValue Vec = Op.getOperand(0);
04357     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
04358                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
04359     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
04360                        DAG.getIntPtrConstant(0));
04361   }
04362 
04363   return SDValue();
04364 }
04365 
04366 SDValue
04367 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
04368   MVT VT = Op.getValueType();
04369   MVT EVT = VT.getVectorElementType();
04370 
04371   SDValue N0 = Op.getOperand(0);
04372   SDValue N1 = Op.getOperand(1);
04373   SDValue N2 = Op.getOperand(2);
04374 
04375   if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
04376       isa<ConstantSDNode>(N2)) {
04377     unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
04378                                                   : X86ISD::PINSRW;
04379     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
04380     // argument.
04381     if (N1.getValueType() != MVT::i32)
04382       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
04383     if (N2.getValueType() != MVT::i32)
04384       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
04385     return DAG.getNode(Opc, VT, N0, N1, N2);
04386   } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
04387     // Bits [7:6] of the constant are the source select.  This will always be
04388     //  zero here.  The DAG Combiner may combine an extract_elt index into these
04389     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
04390     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
04391     // Bits [5:4] of the constant are the destination select.  This is the 
04392     //  value of the incoming immediate.
04393     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may 
04394     //   combine either bitwise AND or insert of float 0.0 to set these bits.
04395     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
04396     return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
04397   } else if (EVT == MVT::i32) {
04398     // InsertPS works with constant index.
04399     if (isa<ConstantSDNode>(N2))
04400       return Op;
04401   }
04402   return SDValue();
04403 }
04404 
04405 SDValue
04406 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
04407   MVT VT = Op.getValueType();
04408   MVT EVT = VT.getVectorElementType();
04409 
04410   if (Subtarget->hasSSE41())
04411     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
04412 
04413   if (EVT == MVT::i8)
04414     return SDValue();
04415 
04416   SDValue N0 = Op.getOperand(0);
04417   SDValue N1 = Op.getOperand(1);
04418   SDValue N2 = Op.getOperand(2);
04419 
04420   if (EVT.getSizeInBits() == 16) {
04421     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
04422     // as its second argument.
04423     if (N1.getValueType() != MVT::i32)
04424       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
04425     if (N2.getValueType() != MVT::i32)
04426       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
04427     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
04428   }
04429   return SDValue();
04430 }
04431 
04432 SDValue
04433 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
04434   if (Op.getValueType() == MVT::v2f32)
04435     return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
04436                        DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
04437                                    DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
04438                                                Op.getOperand(0))));
04439 
04440   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
04441   MVT VT = MVT::v2i32;
04442   switch (Op.getValueType().getSimpleVT()) {
04443   default: break;
04444   case MVT::v16i8:
04445   case MVT::v8i16:
04446     VT = MVT::v4i32;
04447     break;
04448   }
04449   return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
04450                      DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
04451 }
04452 
04453 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
04454 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
04455 // one of the above mentioned nodes. It has to be wrapped because otherwise
04456 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
04457 // be used to form addressing mode. These wrapped nodes will be selected
04458 // into MOV32ri.
04459 SDValue
04460 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
04461   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
04462   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
04463                                                getPointerTy(),
04464                                                CP->getAlignment());
04465   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
04466   // With PIC, the address is actually $g + Offset.
04467   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
04468       !Subtarget->isPICStyleRIPRel()) {
04469     Result = DAG.getNode(ISD::ADD, getPointerTy(),
04470                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
04471                          Result);
04472   }
04473 
04474   return Result;
04475 }
04476 
04477 SDValue
04478 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
04479                                       int64_t Offset,
04480                                       SelectionDAG &DAG) const {
04481   bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
04482   bool ExtraLoadRequired =
04483     Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
04484 
04485   // Create the TargetGlobalAddress node, folding in the constant
04486   // offset if it is legal.
04487   SDValue Result;
04488   if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
04489     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
04490     Offset = 0;
04491   } else
04492     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
04493   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
04494 
04495   // With PIC, the address is actually $g + Offset.
04496   if (IsPic && !Subtarget->isPICStyleRIPRel()) {
04497     Result = DAG.getNode(ISD::ADD, getPointerTy(),
04498                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
04499                          Result);
04500   }
04501   
04502   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
04503   // load the value at address GV, not the value of GV itself. This means that
04504   // the GlobalAddress must be in the base or index register of the address, not
04505   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
04506   // The same applies for external symbols during PIC codegen
04507   if (ExtraLoadRequired)
04508     Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
04509                          PseudoSourceValue::getGOT(), 0);
04510 
04511   // If there was a non-zero offset that we didn't fold, create an explicit
04512   // addition for it.
04513   if (Offset != 0)
04514     Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
04515                          DAG.getConstant(Offset, getPointerTy()));
04516 
04517   return Result;
04518 }
04519 
04520 SDValue
04521 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
04522   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
04523   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
04524   return LowerGlobalAddress(GV, Offset, DAG);
04525 }
04526 
04527 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
04528 static SDValue
04529 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
04530                                 const MVT PtrVT) {
04531   SDValue InFlag;
04532   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
04533                                      DAG.getNode(X86ISD::GlobalBaseReg,
04534                                                  PtrVT), InFlag);
04535   InFlag = Chain.getValue(1);
04536 
04537   // emit leal symbol@TLSGD(,%ebx,1), %eax
04538   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
04539   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
04540                                              GA->getValueType(0),
04541                                              GA->getOffset());
04542   SDValue Ops[] = { Chain,  TGA, InFlag };
04543   SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
04544   InFlag = Result.getValue(2);
04545   Chain = Result.getValue(1);
04546 
04547   // call ___tls_get_addr. This function receives its argument in
04548   // the register EAX.
04549   Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
04550   InFlag = Chain.getValue(1);
04551 
04552   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
04553   SDValue Ops1[] = { Chain,
04554                       DAG.getTargetExternalSymbol("___tls_get_addr",
04555                                                   PtrVT),
04556                       DAG.getRegister(X86::EAX, PtrVT),
04557                       DAG.getRegister(X86::EBX, PtrVT),
04558                       InFlag };
04559   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
04560   InFlag = Chain.getValue(1);
04561 
04562   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
04563 }
04564 
04565 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
04566 static SDValue
04567 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
04568                                 const MVT PtrVT) {
04569   SDValue InFlag, Chain;
04570 
04571   // emit leaq symbol@TLSGD(%rip), %rdi
04572   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
04573   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
04574                                              GA->getValueType(0),
04575                                              GA->getOffset());
04576   SDValue Ops[]  = { DAG.getEntryNode(), TGA};
04577   SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
04578   Chain  = Result.getValue(1);
04579   InFlag = Result.getValue(2);
04580 
04581   // call __tls_get_addr. This function receives its argument in
04582   // the register RDI.
04583   Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
04584   InFlag = Chain.getValue(1);
04585 
04586   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
04587   SDValue Ops1[] = { Chain,
04588                       DAG.getTargetExternalSymbol("__tls_get_addr",
04589                                                   PtrVT),
04590                       DAG.getRegister(X86::RDI, PtrVT),
04591                       InFlag };
04592   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
04593   InFlag = Chain.getValue(1);
04594 
04595   return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
04596 }
04597 
04598 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
04599 // "local exec" model.
04600 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
04601                                      const MVT PtrVT) {
04602   // Get the Thread Pointer
04603   SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
04604   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
04605   // exec)
04606   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
04607                                              GA->getValueType(0),
04608                                              GA->getOffset());
04609   SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
04610 
04611   if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
04612     Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
04613                          PseudoSourceValue::getGOT(), 0);
04614 
04615   // The address of the thread local variable is the add of the thread
04616   // pointer with the offset of the variable.
04617   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
04618 }
04619 
04620 SDValue
04621 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
04622   // TODO: implement the "local dynamic" model
04623   // TODO: implement the "initial exec"model for pic executables
04624   assert(Subtarget->isTargetELF() &&
04625          "TLS not implemented for non-ELF targets");
04626   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
04627   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
04628   // otherwise use the "Local Exec"TLS Model
04629   if (Subtarget->is64Bit()) {
04630     return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
04631   } else {
04632     if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
04633       return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
04634     else
04635       return LowerToTLSExecModel(GA, DAG, getPointerTy());
04636   }
04637 }
04638 
04639 SDValue
04640 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
04641   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
04642   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
04643   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
04644   // With PIC, the address is actually $g + Offset.
04645   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
04646       !Subtarget->isPICStyleRIPRel()) {
04647     Result = DAG.getNode(ISD::ADD, getPointerTy(),
04648                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
04649                          Result);
04650   }
04651 
04652   return Result;
04653 }
04654 
04655 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
04656   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
04657   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
04658   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
04659   // With PIC, the address is actually $g + Offset.
04660   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
04661       !Subtarget->isPICStyleRIPRel()) {
04662     Result = DAG.getNode(ISD::ADD, getPointerTy(),
04663                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
04664                          Result);
04665   }
04666 
04667   return Result;
04668 }
04669 
04670 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
04671 /// take a 2 x i32 value to shift plus a shift amount. 
04672 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
04673   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
04674   MVT VT = Op.getValueType();
04675   unsigned VTBits = VT.getSizeInBits();
04676   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
04677   SDValue ShOpLo = Op.getOperand(0);
04678   SDValue ShOpHi = Op.getOperand(1);
04679   SDValue ShAmt  = Op.getOperand(2);
04680   SDValue Tmp1 = isSRA ?
04681     DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
04682     DAG.getConstant(0, VT);
04683 
04684   SDValue Tmp2, Tmp3;
04685   if (Op.getOpcode() == ISD::SHL_PARTS) {
04686     Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
04687     Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
04688   } else {
04689     Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
04690     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
04691   }
04692 
04693   SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
04694                                   DAG.getConstant(VTBits, MVT::i8));
04695   SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
04696                                AndNode, DAG.getConstant(0, MVT::i8));
04697 
04698   SDValue Hi, Lo;
04699   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
04700   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
04701   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
04702 
04703   if (Op.getOpcode() == ISD::SHL_PARTS) {
04704     Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
04705     Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
04706   } else {
04707     Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
04708     Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
04709   }
04710 
04711   SDValue Ops[2] = { Lo, Hi };
04712   return DAG.getMergeValues(Ops, 2);
04713 }
04714 
04715 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
04716   MVT SrcVT = Op.getOperand(0).getValueType();
04717   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
04718          "Unknown SINT_TO_FP to lower!");
04719   
04720   // These are really Legal; caller falls through into that case.
04721   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
04722     return SDValue();
04723   if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 && 
04724       Subtarget->is64Bit())
04725     return SDValue();
04726   
04727   unsigned Size = SrcVT.getSizeInBits()/8;
04728   MachineFunction &MF = DAG.getMachineFunction();
04729   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
04730   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
04731   SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
04732                                  StackSlot,
04733                                  PseudoSourceValue::getFixedStack(SSFI), 0);
04734 
04735   // Build the FILD
04736   SDVTList Tys;
04737   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
04738   if (useSSE)
04739     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
04740   else
04741     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
04742   SmallVector<SDValue, 8> Ops;
04743   Ops.push_back(Chain);
04744   Ops.push_back(StackSlot);
04745   Ops.push_back(DAG.getValueType(SrcVT));
04746   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
04747                                  Tys, &Ops[0], Ops.size());
04748 
04749   if (useSSE) {
04750     Chain = Result.getValue(1);
04751     SDValue InFlag = Result.getValue(2);
04752 
04753     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
04754     // shouldn't be necessary except that RFP cannot be live across
04755     // multiple blocks. When stackifier is fixed, they can be uncoupled.
04756     MachineFunction &MF = DAG.getMachineFunction();
04757     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
04758     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
04759     Tys = DAG.getVTList(MVT::Other);
04760     SmallVector<SDValue, 8> Ops;
04761     Ops.push_back(Chain);
04762     Ops.push_back(Result);
04763     Ops.push_back(StackSlot);
04764     Ops.push_back(DAG.getValueType(Op.getValueType()));
04765     Ops.push_back(InFlag);
04766     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
04767     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
04768                          PseudoSourceValue::getFixedStack(SSFI), 0);
04769   }
04770 
04771   return Result;
04772 }
04773 
04774 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
04775 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
04776   // This algorithm is not obvious. Here it is in C code, more or less:
04777   /*
04778     double uint64_to_double( uint32_t hi, uint32_t lo ) {
04779       static const __m128i exp = { 0x4330000045300000ULL, 0 };
04780       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
04781 
04782       // Copy ints to xmm registers.
04783       __m128i xh = _mm_cvtsi32_si128( hi );
04784       __m128i xl = _mm_cvtsi32_si128( lo );
04785 
04786       // Combine into low half of a single xmm register.
04787       __m128i x = _mm_unpacklo_epi32( xh, xl );
04788       __m128d d;
04789       double sd;
04790 
04791       // Merge in appropriate exponents to give the integer bits the right
04792       // magnitude.
04793       x = _mm_unpacklo_epi32( x, exp );
04794 
04795       // Subtract away the biases to deal with the IEEE-754 double precision
04796       // implicit 1.
04797       d = _mm_sub_pd( (__m128d) x, bias );
04798 
04799       // All conversions up to here are exact. The correctly rounded result is
04800       // calculated using the current rounding mode using the following
04801       // horizontal add.
04802       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
04803       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
04804                                 // store doesn't really need to be here (except
04805                                 // maybe to zero the other double)
04806       return sd;
04807     }
04808   */
04809 
04810   // Build some magic constants.
04811   std::vector<Constant*> CV0;
04812   CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
04813   CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
04814   CV0.push_back(ConstantInt::get(APInt(32, 0)));
04815   CV0.push_back(ConstantInt::get(APInt(32, 0)));
04816   Constant *C0 = ConstantVector::get(CV0);
04817   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
04818 
04819   std::vector<Constant*> CV1;
04820   CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
04821   CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
04822   Constant *C1 = ConstantVector::get(CV1);
04823   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
04824 
04825   SmallVector<SDValue, 4> MaskVec;
04826   MaskVec.push_back(DAG.getConstant(0, MVT::i32));
04827   MaskVec.push_back(DAG.getConstant(4, MVT::i32));
04828   MaskVec.push_back(DAG.getConstant(1, MVT::i32));
04829   MaskVec.push_back(DAG.getConstant(5, MVT::i32));
04830   SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, &MaskVec[0],
04831                                    MaskVec.size());
04832   SmallVector<SDValue, 4> MaskVec2;
04833   MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
04834   MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
04835   SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec2[0],
04836                                  MaskVec2.size());
04837 
04838   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
04839                             DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
04840                                         Op.getOperand(0),
04841                                         DAG.getIntPtrConstant(1)));
04842   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
04843                             DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
04844                                         Op.getOperand(0),
04845                                         DAG.getIntPtrConstant(0)));
04846   SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
04847                                 XR1, XR2, UnpcklMask);
04848   SDValue CLod0 = DAG.getLoad(MVT::v4i32, DAG.getEntryNode(), CPIdx0,
04849                               PseudoSourceValue::getConstantPool(), 0,
04850                               false, 16);
04851   SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
04852                                Unpck1, CLod0, UnpcklMask);
04853   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Unpck2);
04854   SDValue CLod1 = DAG.getLoad(MVT::v2f64, CLod0.getValue(1), CPIdx1,
04855                               PseudoSourceValue::getConstantPool(), 0,
04856                               false, 16);
04857   SDValue Sub = DAG.getNode(ISD::FSUB, MVT::v2f64, XR2F, CLod1);
04858 
04859   // Add the halves; easiest way is to swap them into another reg first.
04860   SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2f64,
04861                              Sub, Sub, ShufMask);
04862   SDValue Add = DAG.getNode(ISD::FADD, MVT::v2f64, Shuf, Sub);
04863   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64, Add,
04864                      DAG.getIntPtrConstant(0));
04865 }
04866 
04867 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
04868 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
04869   // FP constant to bias correct the final result.
04870   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
04871                                    MVT::f64);
04872 
04873   // Load the 32-bit value into an XMM register.
04874   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
04875                              DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
04876                                          Op.getOperand(0),
04877                                          DAG.getIntPtrConstant(0)));
04878 
04879   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64,
04880                      DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Load),
04881                      DAG.getIntPtrConstant(0));
04882 
04883   // Or the load with the bias.
04884   SDValue Or = DAG.getNode(ISD::OR, MVT::v2i64,
04885                            DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64,
04886                                        DAG.getNode(ISD::SCALAR_TO_VECTOR,
04887                                                    MVT::v2f64, Load)),
04888                            DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64,
04889                                        DAG.getNode(ISD::SCALAR_TO_VECTOR,
04890                                                    MVT::v2f64, Bias)));
04891   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64,
04892                    DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Or),
04893                    DAG.getIntPtrConstant(0));
04894 
04895   // Subtract the bias.
04896   SDValue Sub = DAG.getNode(ISD::FSUB, MVT::f64, Or, Bias);
04897 
04898   // Handle final rounding.
04899   MVT DestVT = Op.getValueType();
04900 
04901   if (DestVT.bitsLT(MVT::f64)) {
04902     return DAG.getNode(ISD::FP_ROUND, DestVT, Sub,
04903                        DAG.getIntPtrConstant(0));
04904   } else if (DestVT.bitsGT(MVT::f64)) {
04905     return DAG.getNode(ISD::FP_EXTEND, DestVT, Sub);
04906   }
04907 
04908   // Handle final rounding.
04909   return Sub;
04910 }
04911 
04912 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
04913   SDValue N0 = Op.getOperand(0);
04914 
04915   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
04916   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
04917   // the optimization here.
04918   if (DAG.SignBitIsZero(N0))
04919     return DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), N0);
04920 
04921   MVT SrcVT = N0.getValueType();
04922   if (SrcVT == MVT::i64) {
04923     // We only handle SSE2 f64 target here; caller can handle the rest.
04924     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
04925       return SDValue();
04926 
04927     return LowerUINT_TO_FP_i64(Op, DAG);
04928   } else if (SrcVT == MVT::i32) {
04929     return LowerUINT_TO_FP_i32(Op, DAG);
04930   }
04931 
04932   assert(0 && "Unknown UINT_TO_FP to lower!");
04933   return SDValue();
04934 }
04935 
04936 std::pair<SDValue,SDValue> X86TargetLowering::
04937 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
04938   assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
04939          Op.getValueType().getSimpleVT() >= MVT::i16 &&
04940          "Unknown FP_TO_SINT to lower!");
04941 
04942   // These are really Legal.
04943   if (Op.getValueType() == MVT::i32 && 
04944       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
04945     return std::make_pair(SDValue(), SDValue());
04946   if (Subtarget->is64Bit() &&
04947       Op.getValueType() == MVT::i64 &&
04948       Op.getOperand(0).getValueType() != MVT::f80)
04949     return std::make_pair(SDValue(), SDValue());
04950 
04951   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
04952   // stack slot.
04953   MachineFunction &MF = DAG.getMachineFunction();
04954   unsigned MemSize = Op.getValueType().getSizeInBits()/8;
04955   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
04956   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
04957   unsigned Opc;
04958   switch (Op.getValueType().getSimpleVT()) {
04959   default: assert(0 && "Invalid FP_TO_SINT to lower!");
04960   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
04961   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
04962   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
04963   }
04964 
04965   SDValue Chain = DAG.getEntryNode();
04966   SDValue Value = Op.getOperand(0);
04967   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
04968     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
04969     Chain = DAG.getStore(Chain, Value, StackSlot,
04970                          PseudoSourceValue::getFixedStack(SSFI), 0);
04971     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
04972     SDValue Ops[] = {
04973       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
04974     };
04975     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
04976     Chain = Value.getValue(1);
04977     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
04978     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
04979   }
04980 
04981   // Build the FP_TO_INT*_IN_MEM
04982   SDValue Ops[] = { Chain, Value, StackSlot };
04983   SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
04984 
04985   return std::make_pair(FIST, StackSlot);
04986 }
04987 
04988 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
04989   std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
04990   SDValue FIST = Vals.first, StackSlot = Vals.second;
04991   if (FIST.getNode() == 0) return SDValue();
04992   
04993   // Load the result.
04994   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
04995 }
04996 
04997 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
04998   MVT VT = Op.getValueType();
04999   MVT EltVT = VT;
05000   if (VT.isVector())
05001     EltVT = VT.getVectorElementType();
05002   std::vector<Constant*> CV;
05003   if (EltVT == MVT::f64) {
05004     Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
05005     CV.push_back(C);
05006     CV.push_back(C);
05007   } else {
05008     Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
05009     CV.push_back(C);
05010     CV.push_back(C);
05011     CV.push_back(C);
05012     CV.push_back(C);
05013   }
05014   Constant *C = ConstantVector::get(CV);
05015   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
05016   SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
05017                                PseudoSourceValue::getConstantPool(), 0,
05018                                false, 16);
05019   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
05020 }
05021 
05022 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
05023   MVT VT = Op.getValueType();
05024   MVT EltVT = VT;
05025   unsigned EltNum = 1;
05026   if (VT.isVector()) {
05027     EltVT = VT.getVectorElementType();
05028     EltNum = VT.getVectorNumElements();
05029   }
05030   std::vector<Constant*> CV;
05031   if (EltVT == MVT::f64) {
05032     Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
05033     CV.push_back(C);
05034     CV.push_back(C);
05035   } else {
05036     Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
05037     CV.push_back(C);
05038     CV.push_back(C);
05039     CV.push_back(C);
05040     CV.push_back(C);
05041   }
05042   Constant *C = ConstantVector::get(CV);
05043   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
05044   SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
05045                                PseudoSourceValue::getConstantPool(), 0,
05046                                false, 16);
05047   if (VT.isVector()) {
05048     return DAG.getNode(ISD::BIT_CONVERT, VT,
05049                        DAG.getNode(ISD::XOR, MVT::v2i64,
05050                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
05051                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
05052   } else {
05053     return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
05054   }
05055 }
05056 
05057 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
05058   SDValue Op0 = Op.getOperand(0);
05059   SDValue Op1 = Op.getOperand(1);
05060   MVT VT = Op.getValueType();
05061   MVT SrcVT = Op1.getValueType();
05062 
05063   // If second operand is smaller, extend it first.
05064   if (SrcVT.bitsLT(VT)) {
05065     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
05066     SrcVT = VT;
05067   }
05068   // And if it is bigger, shrink it first.
05069   if (SrcVT.bitsGT(VT)) {
05070     Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
05071     SrcVT = VT;
05072   }
05073 
05074   // At this point the operands and the result should have the same
05075   // type, and that won't be f80 since that is not custom lowered.
05076 
05077   // First get the sign bit of second operand.
05078   std::vector<Constant*> CV;
05079   if (SrcVT == MVT::f64) {
05080     CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
05081     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
05082   } else {
05083     CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
05084     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
05085     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
05086     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
05087   }
05088   Constant *C = ConstantVector::get(CV);
05089   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
05090   SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
05091                                 PseudoSourceValue::getConstantPool(), 0,
05092                                 false, 16);
05093   SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
05094 
05095   // Shift sign bit right or left if the two operands have different types.
05096   if (SrcVT.bitsGT(VT)) {
05097     // Op0 is MVT::f32, Op1 is MVT::f64.
05098     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
05099     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
05100                           DAG.getConstant(32, MVT::i32));
05101     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
05102     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
05103                           DAG.getIntPtrConstant(0));
05104   }
05105 
05106   // Clear first operand sign bit.
05107   CV.clear();
05108   if (VT == MVT::f64) {
05109     CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
05110     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
05111   } else {
05112     CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
05113     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
05114     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
05115     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
05116   }
05117   C = ConstantVector::get(CV);
05118   CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
05119   SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
05120                                 PseudoSourceValue::getConstantPool(), 0,
05121                                 false, 16);
05122   SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
05123 
05124   // Or the value with the sign bit.
05125   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
05126 }
05127 
05128 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
05129   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
05130   SDValue Op0 = Op.getOperand(0);
05131   SDValue Op1 = Op.getOperand(1);
05132   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
05133   
05134   // Lower (X & (1 << N)) == 0 to BT(X, N).
05135   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
05136   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
05137   if (Op0.getOpcode() == ISD::AND &&
05138       Op0.hasOneUse() &&
05139       Op1.getOpcode() == ISD::Constant &&
05140       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
05141       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
05142     SDValue LHS, RHS;
05143     if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
05144       if (ConstantSDNode *Op010C =
05145             dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
05146         if (Op010C->getZExtValue() == 1) {
05147           LHS = Op0.getOperand(0);
05148           RHS = Op0.getOperand(1).getOperand(1);
05149         }
05150     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
05151       if (ConstantSDNode *Op000C =
05152             dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
05153         if (Op000C->getZExtValue() == 1) {
05154           LHS = Op0.getOperand(1);
05155           RHS = Op0.getOperand(0).getOperand(1);
05156         }
05157     } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
05158       ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
05159       SDValue AndLHS = Op0.getOperand(0);
05160       if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
05161         LHS = AndLHS.getOperand(0);
05162         RHS = AndLHS.getOperand(1);
05163       }
05164     }
05165 
05166     if (LHS.getNode()) {
05167       // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
05168       // instruction.  Since the shift amount is in-range-or-undefined, we know
05169       // that doing a bittest on the i16 value is ok.  We extend to i32 because
05170       // the encoding for the i16 version is larger than the i32 version.
05171       if (LHS.getValueType() == MVT::i8)
05172         LHS = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, LHS);
05173 
05174       // If the operand types disagree, extend the shift amount to match.  Since
05175       // BT ignores high bits (like shifts) we can use anyextend.
05176       if (LHS.getValueType() != RHS.getValueType())
05177         RHS = DAG.getNode(ISD::ANY_EXTEND, LHS.getValueType(), RHS);
05178 
05179       SDValue BT = DAG.getNode(X86ISD::BT, MVT::i32, LHS, RHS);
05180       unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
05181       return DAG.getNode(X86ISD::SETCC, MVT::i8,
05182                          DAG.getConstant(Cond, MVT::i8), BT);
05183     }
05184   }
05185 
05186   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
05187   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
05188     
05189   SDValue Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
05190   return DAG.getNode(X86ISD::SETCC, MVT::i8,
05191                      DAG.getConstant(X86CC, MVT::i8), Cond);
05192 }
05193 
05194 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
05195   SDValue Cond;
05196   SDValue Op0 = Op.getOperand(0);
05197   SDValue Op1 = Op.getOperand(1);
05198   SDValue CC = Op.getOperand(2);
05199   MVT VT = Op.getValueType();
05200   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
05201   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
05202 
05203   if (isFP) {
05204     unsigned SSECC = 8;
05205     MVT VT0 = Op0.getValueType();
05206     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
05207     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
05208     bool Swap = false;
05209 
05210     switch (SetCCOpcode) {
05211     default: break;
05212     case ISD::SETOEQ:
05213     case ISD::SETEQ:  SSECC = 0; break;
05214     case ISD::SETOGT: 
05215     case ISD::SETGT: Swap = true; // Fallthrough
05216     case ISD::SETLT:
05217     case ISD::SETOLT: SSECC = 1; break;
05218     case ISD::SETOGE:
05219     case ISD::SETGE: Swap = true; // Fallthrough
05220     case ISD::SETLE:
05221     case ISD::SETOLE: SSECC = 2; break;
05222     case ISD::SETUO:  SSECC = 3; break;
05223     case ISD::SETUNE:
05224     case ISD::SETNE:  SSECC = 4; break;
05225     case ISD::SETULE: Swap = true;
05226     case ISD::SETUGE: SSECC = 5; break;
05227     case ISD::SETULT: Swap = true;
05228     case ISD::SETUGT: SSECC = 6; break;
05229     case ISD::SETO:   SSECC = 7; break;
05230     }
05231     if (Swap)
05232       std::swap(Op0, Op1);
05233 
05234     // In the two special cases we can't handle, emit two comparisons.
05235     if (SSECC == 8) {
05236       if (SetCCOpcode == ISD::SETUEQ) {
05237         SDValue UNORD, EQ;
05238         UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
05239         EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
05240         return DAG.getNode(ISD::OR, VT, UNORD, EQ);
05241       }
05242       else if (SetCCOpcode == ISD::SETONE) {
05243         SDValue ORD, NEQ;
05244         ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
05245         NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
05246         return DAG.getNode(ISD::AND, VT, ORD, NEQ);
05247       }
05248       assert(0 && "Illegal FP comparison");
05249     }
05250     // Handle all other FP comparisons here.
05251     return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
05252   }
05253   
05254   // We are handling one of the integer comparisons here.  Since SSE only has
05255   // GT and EQ comparisons for integer, swapping operands and multiple
05256   // operations may be required for some comparisons.
05257   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
05258   bool Swap = false, Invert = false, FlipSigns = false;
05259   
05260   switch (VT.getSimpleVT()) {
05261   default: break;
05262   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
05263   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
05264   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
05265   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
05266   }
05267   
05268   switch (SetCCOpcode) {
05269   default: break;
05270   case ISD::SETNE:  Invert = true;
05271   case ISD::SETEQ:  Opc = EQOpc; break;
05272   case ISD::SETLT:  Swap = true;
05273   case ISD::SETGT:  Opc = GTOpc; break;
05274   case ISD::SETGE:  Swap = true;
05275   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
05276   case ISD::SETULT: Swap = true;
05277   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
05278   case ISD::SETUGE: Swap = true;
05279   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
05280   }
05281   if (Swap)
05282     std::swap(Op0, Op1);
05283   
05284   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
05285   // bits of the inputs before performing those operations.
05286   if (FlipSigns) {
05287     MVT EltVT = VT.getVectorElementType();
05288     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
05289                                       EltVT);
05290     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
05291     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
05292                                     SignBits.size());
05293     Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
05294     Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
05295   }
05296   
05297   SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
05298 
05299   // If the logical-not of the result is required, perform that now.
05300   if (Invert)
05301     Result = DAG.getNOT(Op.getDebugLoc(), Result, VT);
05302 
05303   return Result;
05304 }
05305 
05306 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
05307 static bool isX86LogicalCmp(unsigned Opc) {
05308   return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
05309 }
05310 
05311 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
05312   bool addTest = true;
05313   SDValue Cond  = Op.getOperand(0);
05314   SDValue CC;
05315 
05316   if (Cond.getOpcode() == ISD::SETCC)
05317     Cond = LowerSETCC(Cond, DAG);
05318 
05319   // If condition flag is set by a X86ISD::CMP, then use it as the condition
05320   // setting operand in place of the X86ISD::SETCC.
05321   if (Cond.getOpcode() == X86ISD::SETCC) {
05322     CC = Cond.getOperand(0);
05323 
05324     SDValue Cmp = Cond.getOperand(1);
05325     unsigned Opc = Cmp.getOpcode();
05326     MVT VT = Op.getValueType();
05327     
05328     bool IllegalFPCMov = false;
05329     if (VT.isFloatingPoint() && !VT.isVector() &&
05330         !isScalarFPTypeInSSEReg(VT))  // FPStack?
05331       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
05332     
05333     if ((isX86LogicalCmp(Opc) && !IllegalFPCMov) || Opc == X86ISD::BT) { // FIXME
05334       Cond = Cmp;
05335       addTest = false;
05336     }
05337   }
05338 
05339   if (addTest) {
05340     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
05341     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
05342   }
05343 
05344   const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
05345                                                     MVT::Flag);
05346   SmallVector<SDValue, 4> Ops;
05347   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
05348   // condition is true.
05349   Ops.push_back(Op.getOperand(2));
05350   Ops.push_back(Op.getOperand(1));
05351   Ops.push_back(CC);
05352   Ops.push_back(Cond);
05353   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
05354 }
05355 
05356 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
05357 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
05358 // from the AND / OR.
05359 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
05360   Opc = Op.getOpcode();
05361   if (Opc != ISD::OR && Opc != ISD::AND)
05362     return false;
05363   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
05364           Op.getOperand(0).hasOneUse() &&
05365           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
05366           Op.getOperand(1).hasOneUse());
05367 }
05368 
05369 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
05370 // 1 and that the SETCC node has a single use.
05371 static bool isXor1OfSetCC(SDValue Op) {
05372   if (Op.getOpcode() != ISD::XOR)
05373     return false;
05374   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
05375   if (N1C && N1C->getAPIntValue() == 1) {
05376     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
05377       Op.getOperand(0).hasOneUse();
05378   }
05379   return false;
05380 }
05381 
05382 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
05383   bool addTest = true;
05384   SDValue Chain = Op.getOperand(0);
05385   SDValue Cond  = Op.getOperand(1);
05386   SDValue Dest  = Op.getOperand(2);
05387   SDValue CC;
05388 
05389   if (Cond.getOpcode() == ISD::SETCC)
05390     Cond = LowerSETCC(Cond, DAG);
05391 #if 0
05392   // FIXME: LowerXALUO doesn't handle these!!
05393   else if (Cond.getOpcode() == X86ISD::ADD  ||
05394            Cond.getOpcode() == X86ISD::SUB  ||
05395            Cond.getOpcode() == X86ISD::SMUL ||
05396            Cond.getOpcode() == X86ISD::UMUL)
05397     Cond = LowerXALUO(Cond, DAG);
05398 #endif
05399   
05400   // If condition flag is set by a X86ISD::CMP, then use it as the condition
05401   // setting operand in place of the X86ISD::SETCC.
05402   if (Cond.getOpcode() == X86ISD::SETCC) {
05403     CC = Cond.getOperand(0);
05404 
05405     SDValue Cmp = Cond.getOperand(1);
05406     unsigned Opc = Cmp.getOpcode();
05407     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
05408     if (isX86LogicalCmp(Opc) || Opc == X86ISD::BT) {
05409       Cond = Cmp;
05410       addTest = false;
05411     } else {
05412       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
05413       default: break;
05414       case X86::COND_O:
05415       case X86::COND_B:
05416         // These can only come from an arithmetic instruction with overflow,
05417         // e.g. SADDO, UADDO.
05418         Cond = Cond.getNode()->getOperand(1);
05419         addTest = false;
05420         break;
05421       }
05422     }
05423   } else {
05424     unsigned CondOpc;
05425     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
05426       SDValue Cmp = Cond.getOperand(0).getOperand(1);
05427       unsigned Opc = Cmp.getOpcode();
05428       if (CondOpc == ISD::OR) {
05429         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
05430         // two branches instead of an explicit OR instruction with a
05431         // separate test.
05432         if (Cmp == Cond.getOperand(1).getOperand(1) &&
05433             isX86LogicalCmp(Opc)) {
05434           CC = Cond.getOperand(0).getOperand(0);
05435           Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
05436                               Chain, Dest, CC, Cmp);
05437           CC = Cond.getOperand(1).getOperand(0);
05438           Cond = Cmp;
05439           addTest = false;
05440         }
05441       } else { // ISD::AND
05442         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
05443         // two branches instead of an explicit AND instruction with a
05444         // separate test. However, we only do this if this block doesn't
05445         // have a fall-through edge, because this requires an explicit
05446         // jmp when the condition is false.
05447         if (Cmp == Cond.getOperand(1).getOperand(1) &&
05448             isX86LogicalCmp(Opc) &&
05449             Op.getNode()->hasOneUse()) {
05450           X86::CondCode CCode =
05451             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
05452           CCode = X86::GetOppositeBranchCondition(CCode);
05453           CC = DAG.getConstant(CCode, MVT::i8);
05454           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
05455           // Look for an unconditional branch following this conditional branch.
05456           // We need this because we need to reverse the successors in order
05457           // to implement FCMP_OEQ.
05458           if (User.getOpcode() == ISD::BR) {
05459             SDValue FalseBB = User.getOperand(1);
05460             SDValue NewBR =
05461               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
05462             assert(NewBR == User);
05463             Dest = FalseBB;
05464 
05465             Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
05466                                 Chain, Dest, CC, Cmp);
05467             X86::CondCode CCode =
05468               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
05469             CCode = X86::GetOppositeBranchCondition(CCode);
05470             CC = DAG.getConstant(CCode, MVT::i8);
05471             Cond = Cmp;
05472             addTest = false;
05473           }
05474         }
05475       }
05476     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
05477       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
05478       // It should be transformed during dag combiner except when the condition
05479       // is set by a arithmetics with overflow node.
05480       X86::CondCode CCode =
05481         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
05482       CCode = X86::GetOppositeBranchCondition(CCode);
05483       CC = DAG.getConstant(CCode, MVT::i8);
05484       Cond = Cond.getOperand(0).getOperand(1);
05485       addTest = false;
05486     }
05487   }
05488 
05489   if (addTest) {
05490     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
05491     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
05492   }
05493   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
05494                      Chain, Dest, CC, Cond);
05495 }
05496 
05497 
05498 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
05499 // Calls to _alloca is needed to probe the stack when allocating more than 4k
05500 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
05501 // that the guard pages used by the OS virtual memory manager are allocated in
05502 // correct sequence.
05503 SDValue
05504 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
05505                                            SelectionDAG &DAG) {
05506   assert(Subtarget->isTargetCygMing() &&
05507          "This should be used only on Cygwin/Mingw targets");
05508 
05509   // Get the inputs.
05510   SDValue Chain = Op.getOperand(0);
05511   SDValue Size  = Op.getOperand(1);
05512   // FIXME: Ensure alignment here
05513 
05514   SDValue Flag;
05515 
05516   MVT IntPtr = getPointerTy();
05517   MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
05518 
05519   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
05520 
05521   Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
05522   Flag = Chain.getValue(1);
05523 
05524   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
05525   SDValue Ops[] = { Chain,
05526                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
05527                       DAG.getRegister(X86::EAX, IntPtr),
05528                       DAG.getRegister(X86StackPtr, SPTy),
05529                       Flag };
05530   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
05531   Flag = Chain.getValue(1);
05532 
05533   Chain = DAG.getCALLSEQ_END(Chain,
05534                              DAG.getIntPtrConstant(0, true),
05535                              DAG.getIntPtrConstant(0, true),
05536                              Flag);
05537 
05538   Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
05539 
05540   SDValue Ops1[2] = { Chain.getValue(0), Chain };
05541   return DAG.getMergeValues(Ops1, 2);
05542 }
05543 
05544 SDValue
05545 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
05546                                            SDValue Chain,
05547                                            SDValue Dst, SDValue Src,
05548                                            SDValue Size, unsigned Align,
05549                                            const Value *DstSV,
05550                                            uint64_t DstSVOff) {
05551   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
05552 
05553   // If not DWORD aligned or size is more than the threshold, call the library.
05554   // The libc version is likely to be faster for these cases. It can use the
05555   // address value and run time information about the CPU.
05556   if ((Align & 3) != 0 ||
05557       !ConstantSize ||
05558       ConstantSize->getZExtValue() >
05559         getSubtarget()->getMaxInlineSizeThreshold()) {
05560     SDValue InFlag(0, 0);
05561 
05562     // Check to see if there is a specialized entry-point for memory zeroing.
05563     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
05564 
05565     if (const char *bzeroEntry =  V &&
05566         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
05567       MVT IntPtr = getPointerTy();
05568       const Type *IntPtrTy = TD->getIntPtrType();
05569       TargetLowering::ArgListTy Args; 
05570       TargetLowering::ArgListEntry Entry;
05571       Entry.Node = Dst;
05572       Entry.Ty = IntPtrTy;
05573       Args.push_back(Entry);
05574       Entry.Node = Size;
05575       Args.push_back(Entry);
05576       // FIXME provide DebugLoc info
05577       std::pair<SDValue,SDValue> CallResult =
05578         LowerCallTo(Chain, Type::VoidTy, false, false, false, false, 
05579                     CallingConv::C, false, 
05580                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG,
05581                     DebugLoc::getUnknownLoc());
05582       return CallResult.second;
05583     }
05584 
05585     // Otherwise have the target-independent code call memset.
05586     return SDValue();
05587   }
05588 
05589   uint64_t SizeVal = ConstantSize->getZExtValue();
05590   SDValue InFlag(0, 0);
05591   MVT AVT;
05592   SDValue Count;
05593   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
05594   unsigned BytesLeft = 0;
05595   bool TwoRepStos = false;
05596   if (ValC) {
05597     unsigned ValReg;
05598     uint64_t Val = ValC->getZExtValue() & 255;
05599 
05600     // If the value is a constant, then we can potentially use larger sets.
05601     switch (Align & 3) {
05602     case 2:   // WORD aligned
05603       AVT = MVT::i16;
05604       ValReg = X86::AX;
05605       Val = (Val << 8) | Val;
05606       break;
05607     case 0:  // DWORD aligned
05608       AVT = MVT::i32;
05609       ValReg = X86::EAX;
05610       Val = (Val << 8)  | Val;
05611       Val = (Val << 16) | Val;
05612       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
05613         AVT = MVT::i64;
05614         ValReg = X86::RAX;
05615         Val = (Val << 32) | Val;
05616       }
05617       break;
05618     default:  // Byte aligned
05619       AVT = MVT::i8;
05620       ValReg = X86::AL;
05621       Count = DAG.getIntPtrConstant(SizeVal);
05622       break;
05623     }
05624 
05625     if (AVT.bitsGT(MVT::i8)) {
05626       unsigned UBytes = AVT.getSizeInBits() / 8;
05627       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
05628       BytesLeft = SizeVal % UBytes;
05629     }
05630 
05631     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
05632                               InFlag);
05633     InFlag = Chain.getValue(1);
05634   } else {
05635     AVT = MVT::i8;
05636     Count  = DAG.getIntPtrConstant(SizeVal);
05637     Chain  = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
05638     InFlag = Chain.getValue(1);
05639   }
05640 
05641   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
05642                             Count, InFlag);
05643   InFlag = Chain.getValue(1);
05644   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
05645                             Dst, InFlag);
05646   InFlag = Chain.getValue(1);
05647 
05648   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
05649   SmallVector<SDValue, 8> Ops;
05650   Ops.push_back(Chain);
05651   Ops.push_back(DAG.getValueType(AVT));
05652   Ops.push_back(InFlag);
05653   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
05654 
05655   if (TwoRepStos) {
05656     InFlag = Chain.getValue(1);
05657     Count  = Size;
05658     MVT CVT = Count.getValueType();
05659     SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
05660                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
05661     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
05662                               Left, InFlag);
05663     InFlag = Chain.getValue(1);
05664     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
05665     Ops.clear();
05666     Ops.push_back(Chain);
05667     Ops.push_back(DAG.getValueType(MVT::i8));
05668     Ops.push_back(InFlag);
05669     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
05670   } else if (BytesLeft) {
05671     // Handle the last 1 - 7 bytes.
05672     unsigned Offset = SizeVal - BytesLeft;
05673     MVT AddrVT = Dst.getValueType();
05674     MVT SizeVT = Size.getValueType();
05675 
05676     Chain = DAG.getMemset(Chain,
05677                           DAG.getNode(ISD::ADD, AddrVT, Dst,
05678                                       DAG.getConstant(Offset, AddrVT)),
05679                           Src,
05680                           DAG.getConstant(BytesLeft, SizeVT),
05681                           Align, DstSV, DstSVOff + Offset);
05682   }
05683 
05684   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
05685   return Chain;
05686 }
05687 
05688 SDValue
05689 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
05690                                       SDValue Chain, SDValue Dst, SDValue Src,
05691                                       SDValue Size, unsigned Align,
05692                                       bool AlwaysInline,
05693                                       const Value *DstSV, uint64_t DstSVOff,
05694                                       const Value *SrcSV, uint64_t SrcSVOff) {  
05695   // This requires the copy size to be a constant, preferrably
05696   // within a subtarget-specific limit.
05697   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
05698   if (!ConstantSize)
05699     return SDValue();
05700   uint64_t SizeVal = ConstantSize->getZExtValue();
05701   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
05702     return SDValue();
05703 
05704   /// If not DWORD aligned, call the library.
05705   if ((Align & 3) != 0)
05706     return SDValue();
05707 
05708   // DWORD aligned
05709   MVT AVT = MVT::i32;
05710   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
05711     AVT = MVT::i64;
05712 
05713   unsigned UBytes = AVT.getSizeInBits() / 8;
05714   unsigned CountVal = SizeVal / UBytes;
05715   SDValue Count = DAG.getIntPtrConstant(CountVal);
05716   unsigned BytesLeft = SizeVal % UBytes;
05717 
05718   SDValue InFlag(0, 0);
05719   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
05720                             Count, InFlag);
05721   InFlag = Chain.getValue(1);
05722   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
05723                             Dst, InFlag);
05724   InFlag = Chain.getValue(1);
05725   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
05726                             Src, InFlag);
05727   InFlag = Chain.getValue(1);
05728 
05729   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
05730   SmallVector<SDValue, 8> Ops;
05731   Ops.push_back(Chain);
05732   Ops.push_back(DAG.getValueType(AVT));
05733   Ops.push_back(InFlag);
05734   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
05735 
05736   SmallVector<SDValue, 4> Results;
05737   Results.push_back(RepMovs);
05738   if (BytesLeft) {
05739     // Handle the last 1 - 7 bytes.
05740     unsigned Offset = SizeVal - BytesLeft;
05741     MVT DstVT = Dst.getValueType();
05742     MVT SrcVT = Src.getValueType();
05743     MVT SizeVT = Size.getValueType();
05744     Results.push_back(DAG.getMemcpy(Chain,
05745                                     DAG.getNode(ISD::ADD, DstVT, Dst,
05746                                                 DAG.getConstant(Offset, DstVT)),
05747                                     DAG.getNode(ISD::ADD, SrcVT, Src,
05748                                                 DAG.getConstant(Offset, SrcVT)),
05749                                     DAG.getConstant(BytesLeft, SizeVT),
05750                                     Align, AlwaysInline,
05751                                     DstSV, DstSVOff + Offset,
05752                                     SrcSV, SrcSVOff + Offset));
05753   }
05754 
05755   return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
05756 }
05757 
05758 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
05759   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
05760 
05761   if (!Subtarget->is64Bit()) {
05762     // vastart just stores the address of the VarArgsFrameIndex slot into the
05763     // memory location argument.
05764     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
05765     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
05766   }
05767 
05768   // __va_list_tag:
05769   //   gp_offset         (0 - 6 * 8)
05770   //   fp_offset         (48 - 48 + 8 * 16)
05771   //   overflow_arg_area (point to parameters coming in memory).
05772   //   reg_save_area
05773   SmallVector<SDValue, 8> MemOps;
05774   SDValue FIN = Op.getOperand(1);
05775   // Store gp_offset
05776   SDValue Store = DAG.getStore(Op.getOperand(0),
05777                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
05778                                  FIN, SV, 0);
05779   MemOps.push_back(Store);
05780 
05781   // Store fp_offset
05782   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
05783   Store = DAG.getStore(Op.getOperand(0),
05784                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
05785                        FIN, SV, 0);
05786   MemOps.push_back(Store);
05787 
05788   // Store ptr to overflow_arg_area
05789   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
05790   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
05791   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
05792   MemOps.push_back(Store);
05793 
05794   // Store ptr to reg_save_area.
05795   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
05796   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
05797   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
05798   MemOps.push_back(Store);
05799   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
05800 }
05801 
05802 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
05803   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
05804   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
05805   SDValue Chain = Op.getOperand(0);
05806   SDValue SrcPtr = Op.getOperand(1);
05807   SDValue SrcSV = Op.getOperand(2);
05808 
05809   assert(0 && "VAArgInst is not yet implemented for x86-64!");
05810   abort();
05811   return SDValue();
05812 }
05813 
05814 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
05815   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
05816   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
05817   SDValue Chain = Op.getOperand(0);
05818   SDValue DstPtr = Op.getOperand(1);
05819   SDValue SrcPtr = Op.getOperand(2);
05820   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
05821   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
05822 
05823   return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
05824                        DAG.getIntPtrConstant(24), 8, false,
05825                        DstSV, 0, SrcSV, 0);
05826 }
05827 
05828 SDValue
05829 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
05830   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
05831   switch (IntNo) {
05832   default: return SDValue();    // Don't custom lower most intrinsics.
05833   // Comparison intrinsics.
05834   case Intrinsic::x86_sse_comieq_ss:
05835   case Intrinsic::x86_sse_comilt_ss:
05836   case Intrinsic::x86_sse_comile_ss:
05837   case Intrinsic::x86_sse_comigt_ss:
05838   case Intrinsic::x86_sse_comige_ss:
05839   case Intrinsic::x86_sse_comineq_ss:
05840   case Intrinsic::x86_sse_ucomieq_ss:
05841   case Intrinsic::x86_sse_ucomilt_ss:
05842   case Intrinsic::x86_sse_ucomile_ss:
05843   case Intrinsic::x86_sse_ucomigt_ss:
05844   case Intrinsic::x86_sse_ucomige_ss:
05845   case Intrinsic::x86_sse_ucomineq_ss:
05846   case Intrinsic::x86_sse2_comieq_sd:
05847   case Intrinsic::x86_sse2_comilt_sd:
05848   case Intrinsic::x86_sse2_comile_sd:
05849   case Intrinsic::x86_sse2_comigt_sd:
05850   case Intrinsic::x86_sse2_comige_sd:
05851   case Intrinsic::x86_sse2_comineq_sd:
05852   case Intrinsic::x86_sse2_ucomieq_sd:
05853   case Intrinsic::x86_sse2_ucomilt_sd:
05854   case Intrinsic::x86_sse2_ucomile_sd:
05855   case Intrinsic::x86_sse2_ucomigt_sd:
05856   case Intrinsic::x86_sse2_ucomige_sd:
05857   case Intrinsic::x86_sse2_ucomineq_sd: {
05858     unsigned Opc = 0;
05859     ISD::CondCode CC = ISD::SETCC_INVALID;
05860     switch (IntNo) {
05861     default: break;
05862     case Intrinsic::x86_sse_comieq_ss:
05863     case Intrinsic::x86_sse2_comieq_sd:
05864       Opc = X86ISD::COMI;
05865       CC = ISD::SETEQ;
05866       break;
05867     case Intrinsic::x86_sse_comilt_ss:
05868     case Intrinsic::x86_sse2_comilt_sd:
05869       Opc = X86ISD::COMI;
05870       CC = ISD::SETLT;
05871       break;
05872     case Intrinsic::x86_sse_comile_ss:
05873     case Intrinsic::x86_sse2_comile_sd:
05874       Opc = X86ISD::COMI;
05875       CC = ISD::SETLE;
05876       break;
05877     case Intrinsic::x86_sse_comigt_ss:
05878     case Intrinsic::x86_sse2_comigt_sd:
05879       Opc = X86ISD::COMI;
05880       CC = ISD::SETGT;
05881       break;
05882     case Intrinsic::x86_sse_comige_ss:
05883     case Intrinsic::x86_sse2_comige_sd:
05884       Opc = X86ISD::COMI;
05885       CC = ISD::SETGE;
05886       break;
05887     case Intrinsic::x86_sse_comineq_ss:
05888     case Intrinsic::x86_sse2_comineq_sd:
05889       Opc = X86ISD::COMI;
05890       CC = ISD::SETNE;
05891       break;
05892     case Intrinsic::x86_sse_ucomieq_ss:
05893     case Intrinsic::x86_sse2_ucomieq_sd:
05894       Opc = X86ISD::UCOMI;
05895       CC = ISD::SETEQ;
05896       break;
05897     case Intrinsic::x86_sse_ucomilt_ss:
05898     case Intrinsic::x86_sse2_ucomilt_sd:
05899       Opc = X86ISD::UCOMI;
05900       CC = ISD::SETLT;
05901       break;
05902     case Intrinsic::x86_sse_ucomile_ss:
05903     case Intrinsic::x86_sse2_ucomile_sd:
05904       Opc = X86ISD::UCOMI;
05905       CC = ISD::SETLE;
05906       break;
05907     case Intrinsic::x86_sse_ucomigt_ss:
05908     case Intrinsic::x86_sse2_ucomigt_sd:
05909       Opc = X86ISD::UCOMI;
05910       CC = ISD::SETGT;
05911       break;
05912     case Intrinsic::x86_sse_ucomige_ss:
05913     case Intrinsic::x86_sse2_ucomige_sd:
05914       Opc = X86ISD::UCOMI;
05915       CC = ISD::SETGE;
05916       break;
05917     case Intrinsic::x86_sse_ucomineq_ss:
05918     case Intrinsic::x86_sse2_ucomineq_sd:
05919       Opc = X86ISD::UCOMI;
05920       CC = ISD::SETNE;
05921       break;
05922     }
05923 
05924     SDValue LHS = Op.getOperand(1);
05925     SDValue RHS = Op.getOperand(2);
05926     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
05927     SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
05928     SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
05929                                 DAG.getConstant(X86CC, MVT::i8), Cond);
05930     return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
05931   }
05932 
05933   // Fix vector shift instructions where the last operand is a non-immediate
05934   // i32 value.
05935   case Intrinsic::x86_sse2_pslli_w:
05936   case Intrinsic::x86_sse2_pslli_d:
05937   case Intrinsic::x86_sse2_pslli_q:
05938   case Intrinsic::x86_sse2_psrli_w:
05939   case Intrinsic::x86_sse2_psrli_d:
05940   case Intrinsic::x86_sse2_psrli_q:
05941   case Intrinsic::x86_sse2_psrai_w:
05942   case Intrinsic::x86_sse2_psrai_d:
05943   case Intrinsic::x86_mmx_pslli_w:
05944   case Intrinsic::x86_mmx_pslli_d:
05945   case Intrinsic::x86_mmx_pslli_q:
05946   case Intrinsic::x86_mmx_psrli_w:
05947   case Intrinsic::x86_mmx_psrli_d:
05948   case Intrinsic::x86_mmx_psrli_q:
05949   case Intrinsic::x86_mmx_psrai_w:
05950   case Intrinsic::x86_mmx_psrai_d: {
05951     SDValue ShAmt = Op.getOperand(2);
05952     if (isa<ConstantSDNode>(ShAmt))
05953       return SDValue();
05954 
05955     unsigned NewIntNo = 0;
05956     MVT ShAmtVT = MVT::v4i32;
05957     switch (IntNo) {
05958     case Intrinsic::x86_sse2_pslli_w:
05959       NewIntNo = Intrinsic::x86_sse2_psll_w;
05960       break;
05961     case Intrinsic::x86_sse2_pslli_d:
05962       NewIntNo = Intrinsic::x86_sse2_psll_d;
05963       break;
05964     case Intrinsic::x86_sse2_pslli_q:
05965       NewIntNo = Intrinsic::x86_sse2_psll_q;
05966       break;
05967     case Intrinsic::x86_sse2_psrli_w:
05968       NewIntNo = Intrinsic::x86_sse2_psrl_w;
05969       break;
05970     case Intrinsic::x86_sse2_psrli_d:
05971       NewIntNo = Intrinsic::x86_sse2_psrl_d;
05972       break;
05973     case Intrinsic::x86_sse2_psrli_q:
05974       NewIntNo = Intrinsic::x86_sse2_psrl_q;
05975       break;
05976     case Intrinsic::x86_sse2_psrai_w:
05977       NewIntNo = Intrinsic::x86_sse2_psra_w;
05978       break;
05979     case Intrinsic::x86_sse2_psrai_d:
05980       NewIntNo = Intrinsic::x86_sse2_psra_d;
05981       break;
05982     default: {
05983       ShAmtVT = MVT::v2i32;
05984       switch (IntNo) {
05985       case Intrinsic::x86_mmx_pslli_w:
05986         NewIntNo = Intrinsic::x86_mmx_psll_w;
05987         break;
05988       case Intrinsic::x86_mmx_pslli_d:
05989         NewIntNo = Intrinsic::x86_mmx_psll_d;
05990         break;
05991       case Intrinsic::x86_mmx_pslli_q:
05992         NewIntNo = Intrinsic::x86_mmx_psll_q;
05993         break;
05994       case Intrinsic::x86_mmx_psrli_w:
05995         NewIntNo = Intrinsic::x86_mmx_psrl_w;
05996         break;
05997       case Intrinsic::x86_mmx_psrli_d:
05998         NewIntNo = Intrinsic::x86_mmx_psrl_d;
05999         break;
06000       case Intrinsic::x86_mmx_psrli_q:
06001         NewIntNo = Intrinsic::x86_mmx_psrl_q;
06002         break;
06003       case Intrinsic::x86_mmx_psrai_w:
06004         NewIntNo = Intrinsic::x86_mmx_psra_w;
06005         break;
06006       case Intrinsic::x86_mmx_psrai_d:
06007         NewIntNo = Intrinsic::x86_mmx_psra_d;
06008         break;
06009       default: abort();  // Can't reach here.
06010       }
06011       break;
06012     }
06013     }
06014     MVT VT = Op.getValueType();
06015     ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
06016                         DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
06017     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
06018                        DAG.getConstant(NewIntNo, MVT::i32),
06019                        Op.getOperand(1), ShAmt);
06020   }
06021   }
06022 }
06023 
06024 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
06025   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
06026 
06027   if (Depth > 0) {
06028     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
06029     SDValue Offset =
06030       DAG.getConstant(TD->getPointerSize(),
06031                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
06032     return DAG.getLoad(getPointerTy(), DAG.getEntryNode(),
06033                        DAG.getNode(ISD::ADD, getPointerTy(), FrameAddr, Offset),
06034                        NULL, 0);
06035   }
06036 
06037   // Just load the return address.
06038   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
06039   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
06040 }
06041 
06042 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
06043   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
06044   MFI->setFrameAddressIsTaken(true);
06045   MVT VT = Op.getValueType();
06046   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
06047   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
06048   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), FrameReg, VT);
06049   while (Depth--)
06050     FrameAddr = DAG.getLoad(VT, DAG.getEntryNode(), FrameAddr, NULL, 0);
06051   return FrameAddr;
06052 }
06053 
06054 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
06055                                                      SelectionDAG &DAG) {
06056   return DAG.getIntPtrConstant(2*TD->getPointerSize());
06057 }
06058 
06059 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
06060 {
06061   MachineFunction &MF = DAG.getMachineFunction();
06062   SDValue Chain     = Op.getOperand(0);
06063   SDValue Offset    = Op.getOperand(1);
06064   SDValue Handler   = Op.getOperand(2);
06065 
06066   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
06067                                   getPointerTy());
06068   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
06069 
06070   SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
06071                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
06072   StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
06073   Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
06074   Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
06075   MF.getRegInfo().addLiveOut(StoreAddrReg);
06076 
06077   return DAG.getNode(X86ISD::EH_RETURN,
06078                      MVT::Other,
06079                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
06080 }
06081 
06082 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
06083                                              SelectionDAG &DAG) {
06084   SDValue Root = Op.getOperand(0);
06085   SDValue Trmp = Op.getOperand(1); // trampoline
06086   SDValue FPtr = Op.getOperand(2); // nested function
06087   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
06088 
06089   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
06090 
06091   const X86InstrInfo *TII =
06092     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
06093 
06094   if (Subtarget->is64Bit()) {
06095     SDValue OutChains[6];
06096 
06097     // Large code-model.
06098 
06099     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
06100     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
06101 
06102     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
06103     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
06104 
06105     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
06106 
06107     // Load the pointer to the nested function into R11.
06108     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
06109     SDValue Addr = Trmp;
06110     OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
06111                                 TrmpAddr, 0);
06112 
06113     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
06114     OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
06115 
06116     // Load the 'nest' parameter value into R10.
06117     // R10 is specified in X86CallingConv.td
06118     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
06119     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
06120     OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
06121                                 TrmpAddr, 10);
06122 
06123     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
06124     OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
06125 
06126     // Jump to the nested function.
06127     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
06128     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
06129     OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
06130                                 TrmpAddr, 20);
06131 
06132     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
06133     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
06134     OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
06135                                 TrmpAddr, 22);
06136 
06137     SDValue Ops[] =
06138       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
06139     return DAG.getMergeValues(Ops, 2);
06140   } else {
06141     const Function *Func =
06142       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
06143     unsigned CC = Func->getCallingConv();
06144     unsigned NestReg;
06145 
06146     switch (CC) {
06147     default:
06148       assert(0 && "Unsupported calling convention");
06149     case CallingConv::C:
06150     case CallingConv::X86_StdCall: {
06151       // Pass 'nest' parameter in ECX.
06152       // Must be kept in sync with X86CallingConv.td
06153       NestReg = X86::ECX;
06154 
06155       // Check that ECX wasn't needed by an 'inreg' parameter.
06156       const FunctionType *FTy = Func->getFunctionType();
06157       const AttrListPtr &Attrs = Func->getAttributes();
06158 
06159       if (!Attrs.isEmpty() && !Func->isVarArg()) {
06160         unsigned InRegCount = 0;
06161         unsigned Idx = 1;
06162 
06163         for (FunctionType::param_iterator I = FTy->param_begin(),
06164              E = FTy->param_end(); I != E; ++I, ++Idx)
06165           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
06166             // FIXME: should only count parameters that are lowered to integers.
06167             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
06168 
06169         if (InRegCount > 2) {
06170           cerr << "Nest register in use - reduce number of inreg parameters!\n";
06171           abort();
06172         }
06173       }
06174       break;
06175     }
06176     case CallingConv::X86_FastCall:
06177     case CallingConv::Fast:
06178       // Pass 'nest' parameter in EAX.
06179       // Must be kept in sync with X86CallingConv.td
06180       NestReg = X86::EAX;
06181       break;
06182     }
06183 
06184     SDValue OutChains[4];
06185     SDValue Addr, Disp;
06186 
06187     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
06188     Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
06189 
06190     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
06191     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
06192     OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
06193                                 Trmp, TrmpAddr, 0);
06194 
06195     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
06196     OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
06197 
06198     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
06199     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
06200     OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
06201                                 TrmpAddr, 5, false, 1);
06202 
06203     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
06204     OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
06205 
06206     SDValue Ops[] =
06207       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
06208     return DAG.getMergeValues(Ops, 2);
06209   }
06210 }
06211 
06212 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
06213   /*
06214    The rounding mode is in bits 11:10 of FPSR, and has the following
06215    settings:
06216      00 Round to nearest
06217      01 Round to -inf
06218      10 Round to +inf
06219      11 Round to 0
06220 
06221   FLT_ROUNDS, on the other hand, expects the following:
06222     -1 Undefined
06223      0 Round to 0
06224      1 Round to nearest
06225      2 Round to +inf
06226      3 Round to -inf
06227 
06228   To perform the conversion, we do:
06229     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
06230   */
06231 
06232   MachineFunction &MF = DAG.getMachineFunction();
06233   const TargetMachine &TM = MF.getTarget();
06234   const TargetFrameInfo &TFI = *TM.getFrameInfo();
06235   unsigned StackAlignment = TFI.getStackAlignment();
06236   MVT VT = Op.getValueType();
06237 
06238   // Save FP Control Word to stack slot
06239   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
06240   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
06241 
06242   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
06243                               DAG.getEntryNode(), StackSlot);
06244 
06245   // Load FP Control Word from stack slot
06246   SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
06247 
06248   // Transform as necessary
06249   SDValue CWD1 =
06250     DAG.getNode(ISD::SRL, MVT::i16,
06251                 DAG.getNode(ISD::AND, MVT::i16,
06252                             CWD, DAG.getConstant(0x800, MVT::i16)),
06253                 DAG.getConstant(11, MVT::i8));
06254   SDValue CWD2 =
06255     DAG.getNode(ISD::SRL, MVT::i16,
06256                 DAG.getNode(ISD::AND, MVT::i16,
06257                             CWD, DAG.getConstant(0x400, MVT::i16)),
06258                 DAG.getConstant(9, MVT::i8));
06259 
06260   SDValue RetVal =
06261     DAG.getNode(ISD::AND, MVT::i16,
06262                 DAG.getNode(ISD::ADD, MVT::i16,
06263                             DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
06264                             DAG.getConstant(1, MVT::i16)),
06265                 DAG.getConstant(3, MVT::i16));
06266 
06267 
06268   return DAG.getNode((VT.getSizeInBits() < 16 ?
06269                       ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
06270 }
06271 
06272 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
06273   MVT VT = Op.getValueType();
06274   MVT OpVT = VT;
06275   unsigned NumBits = VT.getSizeInBits();
06276 
06277   Op = Op.getOperand(0);
06278   if (VT == MVT::i8) {
06279     // Zero extend to i32 since there is not an i8 bsr.
06280     OpVT = MVT::i32;
06281     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
06282   }
06283 
06284   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
06285   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
06286   Op = DAG.getNode(X86ISD::BSR, VTs, Op);
06287 
06288   // If src is zero (i.e. bsr sets ZF), returns NumBits.
06289   SmallVector<SDValue, 4> Ops;
06290   Ops.push_back(Op);
06291   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
06292   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
06293   Ops.push_back(Op.getValue(1));
06294   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
06295 
06296   // Finally xor with NumBits-1.
06297   Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
06298 
06299   if (VT == MVT::i8)
06300     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
06301   return Op;
06302 }
06303 
06304 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
06305   MVT VT = Op.getValueType();
06306   MVT OpVT = VT;
06307   unsigned NumBits = VT.getSizeInBits();
06308 
06309   Op = Op.getOperand(0);
06310   if (VT == MVT::i8) {
06311     OpVT = MVT::i32;
06312     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
06313   }
06314 
06315   // Issue a bsf (scan bits forward) which also sets EFLAGS.
06316   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
06317   Op = DAG.getNode(X86ISD::BSF, VTs, Op);
06318 
06319   // If src is zero (i.e. bsf sets ZF), returns NumBits.
06320   SmallVector<SDValue, 4> Ops;
06321   Ops.push_back(Op);
06322   Ops.push_back(DAG.getConstant(NumBits, OpVT));
06323   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
06324   Ops.push_back(Op.getValue(1));
06325   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
06326 
06327   if (VT == MVT::i8)
06328     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
06329   return Op;
06330 }
06331 
06332 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
06333   MVT VT = Op.getValueType();
06334   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
06335   
06336   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
06337   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
06338   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
06339   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
06340   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
06341   //
06342   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
06343   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
06344   //  return AloBlo + AloBhi + AhiBlo;
06345 
06346   SDValue A = Op.getOperand(0);
06347   SDValue B = Op.getOperand(1);
06348   
06349   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
06350                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
06351                        A, DAG.getConstant(32, MVT::i32));
06352   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
06353                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
06354                        B, DAG.getConstant(32, MVT::i32));
06355   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
06356                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
06357                        A, B);
06358   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
06359                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
06360                        A, Bhi);
06361   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
06362                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
06363                        Ahi, B);
06364   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
06365                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
06366                        AloBhi, DAG.getConstant(32, MVT::i32));
06367   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
06368                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
06369                        AhiBlo, DAG.getConstant(32, MVT::i32));
06370   SDValue Res = DAG.getNode(ISD::ADD, VT, AloBlo, AloBhi);
06371   Res = DAG.getNode(ISD::ADD, VT, Res, AhiBlo);
06372   return Res;
06373 }
06374 
06375 
06376 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
06377   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
06378   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
06379   // looks for this combo and may remove the "setcc" instruction if the "setcc"
06380   // has only one use.
06381   SDNode *N = Op.getNode();
06382   SDValue LHS = N->getOperand(0);
06383   SDValue RHS = N->getOperand(1);
06384   unsigned BaseOp = 0;
06385   unsigned Cond = 0;
06386 
06387   switch (Op.getOpcode()) {
06388   default: assert(0 && "Unknown ovf instruction!");
06389   case ISD::SADDO:
06390     BaseOp = X86ISD::ADD;
06391     Cond = X86::COND_O;
06392     break;
06393   case ISD::UADDO:
06394     BaseOp = X86ISD::ADD;
06395     Cond = X86::COND_B;
06396     break;
06397   case ISD::SSUBO:
06398     BaseOp = X86ISD::SUB;
06399     Cond = X86::COND_O;
06400     break;
06401   case ISD::USUBO:
06402     BaseOp = X86ISD::SUB;
06403     Cond = X86::COND_B;
06404     break;
06405   case ISD::SMULO:
06406     BaseOp = X86ISD::SMUL;
06407     Cond = X86::COND_O;
06408     break;
06409   case ISD::UMULO:
06410     BaseOp = X86ISD::UMUL;
06411     Cond = X86::COND_B;
06412     break;
06413   }
06414 
06415   // Also sets EFLAGS.
06416   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
06417   SDValue Sum = DAG.getNode(BaseOp, VTs, LHS, RHS);
06418 
06419   SDValue SetCC =
06420     DAG.getNode(X86ISD::SETCC, N->getValueType(1),
06421                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
06422 
06423   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
06424   return Sum;
06425 }
06426 
06427 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
06428   MVT T = Op.getValueType();
06429   unsigned Reg = 0;
06430   unsigned size = 0;
06431   switch(T.getSimpleVT()) {
06432   default:
06433     assert(false && "Invalid value type!");
06434   case MVT::i8:  Reg = X86::AL;  size = 1; break;
06435   case MVT::i16: Reg = X86::AX;  size = 2; break;
06436   case MVT::i32: Reg = X86::EAX; size = 4; break;
06437   case MVT::i64: 
06438     assert(Subtarget->is64Bit() && "Node not type legal!");
06439     Reg = X86::RAX; size = 8;
06440     break;
06441   }
06442   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
06443                                     Op.getOperand(2), SDValue());
06444   SDValue Ops[] = { cpIn.getValue(0),
06445                     Op.getOperand(1),
06446                     Op.getOperand(3),
06447                     DAG.getTargetConstant(size, MVT::i8),
06448                     cpIn.getValue(1) };
06449   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
06450   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
06451   SDValue cpOut = 
06452     DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
06453   return cpOut;
06454 }
06455 
06456 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
06457                                                  SelectionDAG &DAG) {
06458   assert(Subtarget->is64Bit() && "Result not type legalized?");
06459   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
06460   SDValue TheChain = Op.getOperand(0);
06461   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
06462   SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
06463   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX, MVT::i64,
06464                                    rax.getValue(2));
06465   SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
06466                             DAG.getConstant(32, MVT::i8));
06467   SDValue Ops[] = {
06468     DAG.getNode(ISD::OR, MVT::i64, rax, Tmp),
06469     rdx.getValue(1)
06470   };
06471   return DAG.getMergeValues(Ops, 2);
06472 }
06473 
06474 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
06475   SDNode *Node = Op.getNode();
06476   MVT T = Node->getValueType(0);
06477   SDValue negOp = DAG.getNode(ISD::SUB, T,
06478                                 DAG.getConstant(0, T), Node->getOperand(2));
06479   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD,
06480                        cast<AtomicSDNode>(Node)->getMemoryVT(),
06481                        Node->getOperand(0),
06482                        Node->getOperand(1), negOp,
06483                        cast<AtomicSDNode>(Node)->getSrcValue(),
06484                        cast<AtomicSDNode>(Node)->getAlignment());
06485 }
06486 
06487 /// LowerOperation - Provide custom lowering hooks for some operations.
06488 ///
06489 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
06490   switch (Op.getOpcode()) {
06491   default: assert(0 && "Should not custom lower this!");
06492   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
06493   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
06494   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
06495   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
06496   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
06497   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
06498   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
06499   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
06500   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
06501   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
06502   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
06503   case ISD::SHL_PARTS:
06504   case ISD::SRA_PARTS:
06505   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
06506   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
06507   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
06508   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
06509   case ISD::FABS:               return LowerFABS(Op, DAG);
06510   case ISD::FNEG:               return LowerFNEG(Op, DAG);
06511   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
06512   case ISD::SETCC:              return LowerSETCC(Op, DAG);
06513   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
06514   case ISD::SELECT:             return LowerSELECT(Op, DAG);
06515   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
06516   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
06517   case ISD::CALL:               return LowerCALL(Op, DAG);
06518   case ISD::RET:                return LowerRET(Op, DAG);
06519   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
06520   case ISD::VASTART:            return LowerVASTART(Op, DAG);
06521   case ISD::VAARG:              return LowerVAARG(Op, DAG);
06522   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
06523   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
06524   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
06525   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
06526   case ISD::FRAME_TO_ARGS_OFFSET:
06527                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
06528   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
06529   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
06530   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
06531   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
06532   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
06533   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
06534   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
06535   case ISD::SADDO:
06536   case ISD::UADDO:
06537   case ISD::SSUBO:
06538   case ISD::USUBO:
06539   case ISD::SMULO:
06540   case ISD::UMULO:              return LowerXALUO(Op, DAG);
06541   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
06542   }
06543 }
06544 
06545 void X86TargetLowering::
06546 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
06547                         SelectionDAG &DAG, unsigned NewOp) {
06548   MVT T = Node->getValueType(0);
06549   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
06550 
06551   SDValue Chain = Node->getOperand(0);
06552   SDValue In1 = Node->getOperand(1);
06553   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
06554                              Node->getOperand(2), DAG.getIntPtrConstant(0));
06555   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
06556                              Node->getOperand(2), DAG.getIntPtrConstant(1));
06557   // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
06558   // have a MemOperand.  Pass the info through as a normal operand.
06559   SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
06560   SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
06561   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
06562   SDValue Result = DAG.getNode(NewOp, Tys, Ops, 5);
06563   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
06564   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
06565   Results.push_back(Result.getValue(2));
06566 }
06567 
06568 /// ReplaceNodeResults - Replace a node with an illegal result type
06569 /// with a new node built out of custom code.
06570 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
06571                                            SmallVectorImpl<SDValue>&Results,
06572                                            SelectionDAG &DAG) {
06573   switch (N->getOpcode()) {
06574   default:
06575     assert(false && "Do not know how to custom type legalize this operation!");
06576     return;
06577   case ISD::FP_TO_SINT: {
06578     std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
06579     SDValue FIST = Vals.first, StackSlot = Vals.second;
06580     if (FIST.getNode() != 0) {
06581       MVT VT = N->getValueType(0);
06582       // Return a load from the stack slot.
06583       Results.push_back(DAG.getLoad(VT, FIST, StackSlot, NULL, 0));
06584     }
06585     return;
06586   }
06587   case ISD::READCYCLECOUNTER: {
06588     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
06589     SDValue TheChain = N->getOperand(0);
06590     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
06591     SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
06592     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX, MVT::i32,
06593                                      eax.getValue(2));
06594     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
06595     SDValue Ops[] = { eax, edx };
06596     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2));
06597     Results.push_back(edx.getValue(1));
06598     return;
06599   }
06600   case ISD::ATOMIC_CMP_SWAP: {
06601     MVT T = N->getValueType(0);
06602     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
06603     SDValue cpInL, cpInH;
06604     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
06605                         DAG.getConstant(0, MVT::i32));
06606     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
06607                         DAG.getConstant(1, MVT::i32));
06608     cpInL = DAG.getCopyToReg(N->getOperand(0), X86::EAX, cpInL, SDValue());
06609     cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX, cpInH,
06610                              cpInL.getValue(1));
06611     SDValue swapInL, swapInH;
06612     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
06613                           DAG.getConstant(0, MVT::i32));
06614     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
06615                           DAG.getConstant(1, MVT::i32));
06616     swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX, swapInL,
06617                                cpInH.getValue(1));
06618     swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX, swapInH,
06619                                swapInL.getValue(1));
06620     SDValue Ops[] = { swapInH.getValue(0),
06621                       N->getOperand(1),
06622                       swapInH.getValue(1) };
06623     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
06624     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
06625     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
06626                                         Result.getValue(1));
06627     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
06628                                         cpOutL.getValue(2));
06629     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
06630     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
06631     Results.push_back(cpOutH.getValue(1));
06632     return;
06633   }
06634   case ISD::ATOMIC_LOAD_ADD:
06635     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
06636     return;
06637   case ISD::ATOMIC_LOAD_AND:
06638     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
06639     return;
06640   case ISD::ATOMIC_LOAD_NAND:
06641     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
06642     return;
06643   case ISD::ATOMIC_LOAD_OR:
06644     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
06645     return;
06646   case ISD::ATOMIC_LOAD_SUB:
06647     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
06648     return;
06649   case ISD::ATOMIC_LOAD_XOR:
06650     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
06651     return;
06652   case ISD::ATOMIC_SWAP:
06653     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
06654     return;
06655   }
06656 }
06657 
06658 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
06659   switch (Opcode) {
06660   default: return NULL;
06661   case X86ISD::BSF:                return "X86ISD::BSF";
06662   case X86ISD::BSR:                return "X86ISD::BSR";
06663   case X86ISD::SHLD:               return "X86ISD::SHLD";
06664   case X86ISD::SHRD:               return "X86ISD::SHRD";
06665   case X86ISD::FAND:               return "X86ISD::FAND";
06666   case X86ISD::FOR:                return "X86ISD::FOR";
06667   case X86ISD::FXOR:               return "X86ISD::FXOR";
06668   case X86ISD::FSRL:               return "X86ISD::FSRL";
06669   case X86ISD::FILD:               return "X86ISD::FILD";
06670   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
06671   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
06672   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
06673   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
06674   case X86ISD::FLD:                return "X86ISD::FLD";
06675   case X86ISD::FST:                return "X86ISD::FST";
06676   case X86ISD::CALL:               return "X86ISD::CALL";
06677   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
06678   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
06679   case X86ISD::BT:                 return "X86ISD::BT";
06680   case X86ISD::CMP:                return "X86ISD::CMP";
06681   case X86ISD::COMI:               return "X86ISD::COMI";
06682   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
06683   case X86ISD::SETCC:              return "X86ISD::SETCC";
06684   case X86ISD::CMOV:               return "X86ISD::CMOV";
06685   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
06686   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
06687   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
06688   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
06689   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
06690   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
06691   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
06692   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
06693   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
06694   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
06695   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
06696   case X86ISD::FMAX:               return "X86ISD::FMAX";
06697   case X86ISD::FMIN:               return "X86ISD::FMIN";
06698   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
06699   case X86ISD::FRCP:               return "X86ISD::FRCP";
06700   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
06701   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
06702   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
06703   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
06704   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
06705   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
06706   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
06707   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
06708   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
06709   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
06710   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
06711   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
06712   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
06713   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
06714   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
06715   case X86ISD::VSHL:               return "X86ISD::VSHL";
06716   case X86ISD::VSRL:               return "X86ISD::VSRL";
06717   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
06718   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
06719   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
06720   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
06721   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
06722   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
06723   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
06724   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
06725   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
06726   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
06727   case X86ISD::ADD:                return "X86ISD::ADD";
06728   case X86ISD::SUB:                return "X86ISD::SUB";
06729   case X86ISD::SMUL:               return "X86ISD::SMUL";
06730   case X86ISD::UMUL:               return "X86ISD::UMUL";
06731   }
06732 }
06733 
06734 // isLegalAddressingMode - Return true if the addressing mode represented
06735 // by AM is legal for this target, for a load/store of the specified type.
06736 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
06737                                               const Type *Ty) const {
06738   // X86 supports extremely general addressing modes.
06739   
06740   // X86 allows a sign-extended 32-bit immediate field as a displacement.
06741   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
06742     return false;
06743   
06744   if (AM.BaseGV) {
06745     // We can only fold this if we don't need an extra load.
06746     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
06747       return false;
06748     // If BaseGV requires a register, we cannot also have a BaseReg.
06749     if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
06750         AM.HasBaseReg)
06751       return false;
06752 
06753     // X86-64 only supports addr of globals in small code model.
06754     if (Subtarget->is64Bit()) {
06755       if (getTargetMachine().getCodeModel() != CodeModel::Small)
06756         return false;
06757       // If lower 4G is not available, then we must use rip-relative addressing.
06758       if (AM.BaseOffs || AM.Scale > 1)
06759         return false;
06760     }
06761   }
06762   
06763   switch (AM.Scale) {
06764   case 0:
06765   case 1:
06766   case 2:
06767   case 4:
06768   case 8:
06769     // These scales always work.
06770     break;
06771   case 3:
06772   case 5:
06773   case 9:
06774     // These scales are formed with basereg+scalereg.  Only accept if there is
06775     // no basereg yet.
06776     if (AM.HasBaseReg)
06777       return false;
06778     break;
06779   default:  // Other stuff never works.
06780     return false;
06781   }
06782   
06783   return true;
06784 }
06785 
06786 
06787 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
06788   if (!Ty1->isInteger() || !Ty2->isInteger())
06789     return false;
06790   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
06791   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
06792   if (NumBits1 <= NumBits2)
06793     return false;
06794   return Subtarget->is64Bit() || NumBits1 < 64;
06795 }
06796 
06797 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
06798   if (!VT1.isInteger() || !VT2.isInteger())
06799     return false;
06800   unsigned NumBits1 = VT1.getSizeInBits();
06801   unsigned NumBits2 = VT2.getSizeInBits();
06802   if (NumBits1 <= NumBits2)
06803     return false;
06804   return Subtarget->is64Bit() || NumBits1 < 64;
06805 }
06806 
06807 /// isShuffleMaskLegal - Targets can use this to indicate that they only
06808 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
06809 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
06810 /// are assumed to be legal.
06811 bool
06812 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
06813   // Only do shuffles on 128-bit vector types for now.
06814   if (VT.getSizeInBits() == 64) return false;
06815   return (Mask.getNode()->getNumOperands() <= 4 ||
06816           isIdentityMask(Mask.getNode()) ||
06817           isIdentityMask(Mask.getNode(), true) ||
06818           isSplatMask(Mask.getNode())  ||
06819           isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
06820           X86::isUNPCKLMask(Mask.getNode()) ||
06821           X86::isUNPCKHMask(Mask.getNode()) ||
06822           X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
06823           X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
06824 }
06825 
06826 bool
06827 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
06828                                           MVT EVT, SelectionDAG &DAG) const {
06829   unsigned NumElts = BVOps.size();
06830   // Only do shuffles on 128-bit vector types for now.
06831   if (EVT.getSizeInBits() * NumElts == 64) return false;
06832   if (NumElts == 2) return true;
06833   if (NumElts == 4) {
06834     return (isMOVLMask(&BVOps[0], 4)  ||
06835             isCommutedMOVL(&BVOps[0], 4, true) ||
06836             isSHUFPMask(&BVOps[0], 4) || 
06837             isCommutedSHUFP(&BVOps[0], 4));
06838   }
06839   return false;
06840 }
06841 
06842 //===----------------------------------------------------------------------===//
06843 //                           X86 Scheduler Hooks
06844 //===----------------------------------------------------------------------===//
06845 
06846 // private utility function
06847 MachineBasicBlock *
06848 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
06849                                                        MachineBasicBlock *MBB,
06850                                                        unsigned regOpc,
06851                                                        unsigned immOpc,
06852                                                        unsigned LoadOpc,
06853                                                        unsigned CXchgOpc,
06854                                                        unsigned copyOpc,
06855                                                        unsigned notOpc,
06856                                                        unsigned EAXreg,
06857                                                        TargetRegisterClass *RC,
06858                                                        bool invSrc) {
06859   // For the atomic bitwise operator, we generate
06860   //   thisMBB:
06861   //   newMBB:
06862   //     ld  t1 = [bitinstr.addr]
06863   //     op  t2 = t1, [bitinstr.val]
06864   //     mov EAX = t1
06865   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
06866   //     bz  newMBB
06867   //     fallthrough -->nextMBB
06868   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
06869   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
06870   MachineFunction::iterator MBBIter = MBB;
06871   ++MBBIter;
06872   
06873   /// First build the CFG
06874   MachineFunction *F = MBB->getParent();
06875   MachineBasicBlock *thisMBB = MBB;
06876   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
06877   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
06878   F->insert(MBBIter, newMBB);
06879   F->insert(MBBIter, nextMBB);
06880   
06881   // Move all successors to thisMBB to nextMBB
06882   nextMBB->transferSuccessors(thisMBB);
06883     
06884   // Update thisMBB to fall through to newMBB
06885   thisMBB->addSuccessor(newMBB);
06886   
06887   // newMBB jumps to itself and fall through to nextMBB
06888   newMBB->addSuccessor(nextMBB);
06889   newMBB->addSuccessor(newMBB);
06890   
06891   // Insert instructions into newMBB based on incoming instruction
06892   assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
06893   MachineOperand& destOper = bInstr->getOperand(0);
06894   MachineOperand* argOpers[6];
06895   int numArgs = bInstr->getNumOperands() - 1;
06896   for (int i=0; i < numArgs; ++i)
06897     argOpers[i] = &bInstr->getOperand(i+1);
06898 
06899   // x86 address has 4 operands: base, index, scale, and displacement
06900   int lastAddrIndx = 3; // [0,3]
06901   int valArgIndx = 4;
06902   
06903   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
06904   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
06905   for (int i=0; i <= lastAddrIndx; ++i)
06906     (*MIB).addOperand(*argOpers[i]);
06907 
06908   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
06909   if (invSrc) {
06910     MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
06911   }
06912   else 
06913     tt = t1;
06914 
06915   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
06916   assert((argOpers[valArgIndx]->isReg() ||
06917           argOpers[valArgIndx]->isImm()) &&
06918          "invalid operand");
06919   if (argOpers[valArgIndx]->isReg())
06920     MIB = BuildMI(newMBB, TII->get(regOpc), t2);
06921   else
06922     MIB = BuildMI(newMBB, TII->get(immOpc), t2);
06923   MIB.addReg(tt);
06924   (*MIB).addOperand(*argOpers[valArgIndx]);
06925 
06926   MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
06927   MIB.addReg(t1);
06928   
06929   MIB = BuildMI(newMBB, TII->get(CXchgOpc));
06930   for (int i=0; i <= lastAddrIndx; ++i)
06931     (*MIB).addOperand(*argOpers[i]);
06932   MIB.addReg(t2);
06933   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
06934   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
06935 
06936   MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
06937   MIB.addReg(EAXreg);
06938   
06939   // insert branch
06940   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
06941 
06942   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
06943   return nextMBB;
06944 }
06945 
06946 // private utility function:  64 bit atomics on 32 bit host.
06947 MachineBasicBlock *
06948 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
06949                                                        MachineBasicBlock *MBB,
06950                                                        unsigned regOpcL,
06951                                                        unsigned regOpcH,
06952                                                        unsigned immOpcL,
06953                                                        unsigned immOpcH,
06954                                                        bool invSrc) {
06955   // For the atomic bitwise operator, we generate
06956   //   thisMBB (instructions are in pairs, except cmpxchg8b)
06957   //     ld t1,t2 = [bitinstr.addr]
06958   //   newMBB:
06959   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
06960   //     op  t5, t6 <- out1, out2, [bitinstr.val]
06961   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
06962   //     mov ECX, EBX <- t5, t6
06963   //     mov EAX, EDX <- t1, t2
06964   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
06965   //     mov t3, t4 <- EAX, EDX
06966   //     bz  newMBB
06967   //     result in out1, out2
06968   //     fallthrough -->nextMBB
06969 
06970   const TargetRegisterClass *RC = X86::GR32RegisterClass;
06971   const unsigned LoadOpc = X86::MOV32rm;
06972   const unsigned copyOpc = X86::MOV32rr;
06973   const unsigned NotOpc = X86::NOT32r;
06974   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
06975   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
06976   MachineFunction::iterator MBBIter = MBB;
06977   ++MBBIter;
06978   
06979   /// First build the CFG
06980   MachineFunction *F = MBB->getParent();
06981   MachineBasicBlock *thisMBB = MBB;
06982   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
06983   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
06984   F->insert(MBBIter, newMBB);
06985   F->insert(MBBIter, nextMBB);
06986   
06987   // Move all successors to thisMBB to nextMBB
06988   nextMBB->transferSuccessors(thisMBB);
06989     
06990   // Update thisMBB to fall through to newMBB
06991   thisMBB->addSuccessor(newMBB);
06992   
06993   // newMBB jumps to itself and fall through to nextMBB
06994   newMBB->addSuccessor(nextMBB);
06995   newMBB->addSuccessor(newMBB);
06996   
06997   // Insert instructions into newMBB based on incoming instruction
06998   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
06999   assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
07000   MachineOperand& dest1Oper = bInstr->getOperand(0);
07001   MachineOperand& dest2Oper = bInstr->getOperand(1);
07002   MachineOperand* argOpers[6];
07003   for (int i=0; i < 6; ++i)
07004     argOpers[i] = &bInstr->getOperand(i+2);
07005 
07006   // x86 address has 4 operands: base, index, scale, and displacement
07007   int lastAddrIndx = 3; // [0,3]
07008   
07009   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
07010   MachineInstrBuilder MIB = BuildMI(thisMBB, TII->get(LoadOpc), t1);
07011   for (int i=0; i <= lastAddrIndx; ++i)
07012     (*MIB).addOperand(*argOpers[i]);
07013   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
07014   MIB = BuildMI(thisMBB, TII->get(LoadOpc), t2);
07015   // add 4 to displacement.
07016   for (int i=0; i <= lastAddrIndx-1; ++i)
07017     (*MIB).addOperand(*argOpers[i]);
07018   MachineOperand newOp3 = *(argOpers[3]);
07019   if (newOp3.isImm())
07020     newOp3.setImm(newOp3.getImm()+4);
07021   else
07022     newOp3.setOffset(newOp3.getOffset()+4);
07023   (*MIB).addOperand(newOp3);
07024 
07025   // t3/4 are defined later, at the bottom of the loop
07026   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
07027   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
07028   BuildMI(newMBB, TII->get(X86::PHI), dest1Oper.getReg())
07029     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
07030   BuildMI(newMBB, TII->get(X86::PHI), dest2Oper.getReg())
07031     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
07032 
07033   unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
07034   unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
07035   if (invSrc) {  
07036     MIB = BuildMI(newMBB, TII->get(NotOpc), tt1).addReg(t1);
07037     MIB = BuildMI(newMBB, TII->get(NotOpc), tt2).addReg(t2);
07038   } else {
07039     tt1 = t1;
07040     tt2 = t2;
07041   }
07042 
07043   assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
07044          "invalid operand");
07045   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
07046   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
07047   if (argOpers[4]->isReg())
07048     MIB = BuildMI(newMBB, TII->get(regOpcL), t5);
07049   else
07050     MIB = BuildMI(newMBB, TII->get(immOpcL), t5);
07051   if (regOpcL != X86::MOV32rr)
07052     MIB.addReg(tt1);
07053   (*MIB).addOperand(*argOpers[4]);
07054   assert(argOpers[5]->isReg() == argOpers[4]->isReg());
07055   assert(argOpers[5]->isImm() == argOpers[4]->isImm());
07056   if (argOpers[5]->isReg())
07057     MIB = BuildMI(newMBB, TII->get(regOpcH), t6);
07058   else
07059     MIB = BuildMI(newMBB, TII->get(immOpcH), t6);
07060   if (regOpcH != X86::MOV32rr)
07061     MIB.addReg(tt2);
07062   (*MIB).addOperand(*argOpers[5]);
07063 
07064   MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EAX);
07065   MIB.addReg(t1);
07066   MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EDX);
07067   MIB.addReg(t2);
07068 
07069   MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EBX);
07070   MIB.addReg(t5);
07071   MIB = BuildMI(newMBB, TII->get(copyOpc), X86::ECX);
07072   MIB.addReg(t6);
07073   
07074   MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG8B));
07075   for (int i=0; i <= lastAddrIndx; ++i)
07076     (*MIB).addOperand(*argOpers[i]);
07077 
07078   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
07079   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
07080 
07081   MIB = BuildMI(newMBB, TII->get(copyOpc), t3);
07082   MIB.addReg(X86::EAX);
07083   MIB = BuildMI(newMBB, TII->get(copyOpc), t4);
07084   MIB.addReg(X86::EDX);
07085   
07086   // insert branch
07087   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
07088 
07089   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
07090   return nextMBB;
07091 }
07092 
07093 // private utility function
07094 MachineBasicBlock *
07095 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
07096                                                       MachineBasicBlock *MBB,
07097                                                       unsigned cmovOpc) {
07098   // For the atomic min/max operator, we generate
07099   //   thisMBB:
07100   //   newMBB:
07101   //     ld t1 = [min/max.addr]
07102   //     mov t2 = [min/max.val] 
07103   //     cmp  t1, t2
07104   //     cmov[cond] t2 = t1
07105   //     mov EAX = t1
07106   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
07107   //     bz   newMBB
07108   //     fallthrough -->nextMBB
07109   //
07110   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
07111   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
07112   MachineFunction::iterator MBBIter = MBB;
07113   ++MBBIter;
07114   
07115   /// First build the CFG
07116   MachineFunction *F = MBB->getParent();
07117   MachineBasicBlock *thisMBB = MBB;
07118   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
07119   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
07120   F->insert(MBBIter, newMBB);
07121   F->insert(MBBIter, nextMBB);
07122   
07123   // Move all successors to thisMBB to nextMBB
07124   nextMBB->transferSuccessors(thisMBB);
07125   
07126   // Update thisMBB to fall through to newMBB
07127   thisMBB->addSuccessor(newMBB);
07128   
07129   // newMBB jumps to newMBB and fall through to nextMBB
07130   newMBB->addSuccessor(nextMBB);
07131   newMBB->addSuccessor(newMBB);
07132   
07133   // Insert instructions into newMBB based on incoming instruction
07134   assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
07135   MachineOperand& destOper = mInstr->getOperand(0);
07136   MachineOperand* argOpers[6];
07137   int numArgs = mInstr->getNumOperands() - 1;
07138   for (int i=0; i < numArgs; ++i)
07139     argOpers[i] = &mInstr->getOperand(i+1);
07140   
07141   // x86 address has 4 operands: base, index, scale, and displacement
07142   int lastAddrIndx = 3; // [0,3]
07143   int valArgIndx = 4;
07144   
07145   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
07146   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
07147   for (int i=0; i <= lastAddrIndx; ++i)
07148     (*MIB).addOperand(*argOpers[i]);
07149 
07150   // We only support register and immediate values
07151   assert((argOpers[valArgIndx]->isReg() ||
07152           argOpers[valArgIndx]->isImm()) &&
07153          "invalid operand");
07154   
07155   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);  
07156   if (argOpers[valArgIndx]->isReg())
07157     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
07158   else 
07159     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
07160   (*MIB).addOperand(*argOpers[valArgIndx]);
07161 
07162   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
07163   MIB.addReg(t1);
07164 
07165   MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
07166   MIB.addReg(t1);
07167   MIB.addReg(t2);
07168 
07169   // Generate movc
07170   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
07171   MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
07172   MIB.addReg(t2);
07173   MIB.addReg(t1);
07174 
07175   // Cmp and exchange if none has modified the memory location
07176   MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
07177   for (int i=0; i <= lastAddrIndx; ++i)
07178     (*MIB).addOperand(*argOpers[i]);
07179   MIB.addReg(t3);
07180   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
07181   (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
07182   
07183   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
07184   MIB.addReg(X86::EAX);
07185   
07186   // insert branch
07187   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
07188 
07189   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
07190   return nextMBB;
07191 }
07192 
07193 
07194 MachineBasicBlock *
07195 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
07196                                                MachineBasicBlock *BB) {
07197   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
07198   switch (MI->getOpcode()) {
07199   default: assert(false && "Unexpected instr type to insert");
07200   case X86::CMOV_V1I64:
07201   case X86::CMOV_FR32:
07202   case X86::CMOV_FR64:
07203   case X86::CMOV_V4F32:
07204   case X86::CMOV_V2F64:
07205   case X86::CMOV_V2I64: {
07206     // To "insert" a SELECT_CC instruction, we actually have to insert the
07207     // diamond control-flow pattern.  The incoming instruction knows the
07208     // destination vreg to set, the condition code register to branch on, the
07209     // true/false values to select between, and a branch opcode to use.
07210     const BasicBlock *LLVM_BB = BB->getBasicBlock();
07211     MachineFunction::iterator It = BB;
07212     ++It;
07213 
07214     //  thisMBB:
07215     //  ...
07216     //   TrueVal = ...
07217     //   cmpTY ccX, r1, r2
07218     //   bCC copy1MBB
07219     //   fallthrough --> copy0MBB
07220     MachineBasicBlock *thisMBB = BB;
07221     MachineFunction *F = BB->getParent();
07222     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
07223     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
07224     unsigned Opc =
07225       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
07226     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
07227     F->insert(It, copy0MBB);
07228     F->insert(It, sinkMBB);
07229     // Update machine-CFG edges by transferring all successors of the current
07230     // block to the new block which will contain the Phi node for the select.
07231     sinkMBB->transferSuccessors(BB);
07232 
07233     // Add the true and fallthrough blocks as its successors.
07234     BB->addSuccessor(copy0MBB);
07235     BB->addSuccessor(sinkMBB);
07236 
07237     //  copy0MBB:
07238     //   %FalseValue = ...
07239     //   # fallthrough to sinkMBB
07240     BB = copy0MBB;
07241 
07242     // Update machine-CFG edges
07243     BB->addSuccessor(sinkMBB);
07244 
07245     //  sinkMBB:
07246     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
07247     //  ...
07248     BB = sinkMBB;
07249     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
07250       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
07251       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
07252 
07253     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
07254     return BB;
07255   }
07256 
07257   case X86::FP32_TO_INT16_IN_MEM:
07258   case X86::FP32_TO_INT32_IN_MEM:
07259   case X86::FP32_TO_INT64_IN_MEM:
07260   case X86::FP64_TO_INT16_IN_MEM:
07261   case X86::FP64_TO_INT32_IN_MEM:
07262   case X86::FP64_TO_INT64_IN_MEM:
07263   case X86::FP80_TO_INT16_IN_MEM:
07264   case X86::FP80_TO_INT32_IN_MEM:
07265   case X86::FP80_TO_INT64_IN_MEM: {
07266     // Change the floating point control register to use "round towards zero"
07267     // mode when truncating to an integer value.
07268     MachineFunction *F = BB->getParent();
07269     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
07270     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
07271 
07272     // Load the old value of the high byte of the control word...
07273     unsigned OldCW =
07274       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
07275     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
07276 
07277     // Set the high part to be round to zero...
07278     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
07279       .addImm(0xC7F);
07280 
07281     // Reload the modified control word now...
07282     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
07283 
07284     // Restore the memory image of control word to original value
07285     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
07286       .addReg(OldCW);
07287 
07288     // Get the X86 opcode to use.
07289     unsigned Opc;
07290     switch (MI->getOpcode()) {
07291     default: assert(0 && "illegal opcode!");
07292     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
07293     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
07294     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
07295     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
07296     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
07297     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
07298     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
07299     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
07300     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
07301     }
07302 
07303     X86AddressMode AM;
07304     MachineOperand &Op = MI->getOperand(0);
07305     if (Op.isReg()) {
07306       AM.BaseType = X86AddressMode::RegBase;
07307       AM.Base.Reg = Op.getReg();
07308     } else {
07309       AM.BaseType = X86AddressMode::FrameIndexBase;
07310       AM.Base.FrameIndex = Op.getIndex();
07311     }
07312     Op = MI->getOperand(1);
07313     if (Op.isImm())
07314       AM.Scale = Op.getImm();
07315     Op = MI->getOperand(2);
07316     if (Op.isImm())
07317       AM.IndexReg = Op.getImm();
07318     Op = MI->getOperand(3);
07319     if (Op.isGlobal()) {
07320       AM.GV = Op.getGlobal();
07321     } else {
07322       AM.Disp = Op.getImm();
07323     }
07324     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
07325                       .addReg(MI->getOperand(4).getReg());
07326 
07327     // Reload the original control word now.
07328     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
07329 
07330     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
07331     return BB;
07332   }
07333   case X86::ATOMAND32:
07334     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
07335                                                X86::AND32ri, X86::MOV32rm, 
07336                                                X86::LCMPXCHG32, X86::MOV32rr,
07337                                                X86::NOT32r, X86::EAX,
07338                                                X86::GR32RegisterClass);
07339   case X86::ATOMOR32:
07340     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 
07341                                                X86::OR32ri, X86::MOV32rm, 
07342                                                X86::LCMPXCHG32, X86::MOV32rr,
07343                                                X86::NOT32r, X86::EAX,
07344                                                X86::GR32RegisterClass);
07345   case X86::ATOMXOR32:
07346     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
07347                                                X86::XOR32ri, X86::MOV32rm, 
07348                                                X86::LCMPXCHG32, X86::MOV32rr,
07349                                                X86::NOT32r, X86::EAX,
07350                                                X86::GR32RegisterClass);
07351   case X86::ATOMNAND32:
07352     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
07353                                                X86::AND32ri, X86::MOV32rm,
07354                                                X86::LCMPXCHG32, X86::MOV32rr,
07355                                                X86::NOT32r, X86::EAX,
07356                                                X86::GR32RegisterClass, true);
07357   case X86::ATOMMIN32:
07358     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
07359   case X86::ATOMMAX32:
07360     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
07361   case X86::ATOMUMIN32:
07362     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
07363   case X86::ATOMUMAX32:
07364     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
07365 
07366   case X86::ATOMAND16:
07367     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
07368                                                X86::AND16ri, X86::MOV16rm,
07369                                                X86::LCMPXCHG16, X86::MOV16rr,
07370                                                X86::NOT16r, X86::AX,
07371                                                X86::GR16RegisterClass);
07372   case X86::ATOMOR16:
07373     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 
07374                                                X86::OR16ri, X86::MOV16rm,
07375                                                X86::LCMPXCHG16, X86::MOV16rr,
07376                                                X86::NOT16r, X86::AX,
07377                                                X86::GR16RegisterClass);
07378   case X86::ATOMXOR16:
07379     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
07380                                                X86::XOR16ri, X86::MOV16rm,
07381                                                X86::LCMPXCHG16, X86::MOV16rr,
07382                                                X86::NOT16r, X86::AX,
07383                                                X86::GR16RegisterClass);
07384   case X86::ATOMNAND16:
07385     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
07386                                                X86::AND16ri, X86::MOV16rm,
07387                                                X86::LCMPXCHG16, X86::MOV16rr,
07388                                                X86::NOT16r, X86::AX,
07389                                                X86::GR16RegisterClass, true);
07390   case X86::ATOMMIN16:
07391     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
07392   case X86::ATOMMAX16:
07393     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
07394   case X86::ATOMUMIN16:
07395     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
07396   case X86::ATOMUMAX16:
07397     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
07398 
07399   case X86::ATOMAND8:
07400     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
07401                                                X86::AND8ri, X86::MOV8rm,
07402                                                X86::LCMPXCHG8, X86::MOV8rr,
07403                                                X86::NOT8r, X86::AL,
07404                                                X86::GR8RegisterClass);
07405   case X86::ATOMOR8:
07406     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 
07407                                                X86::OR8ri, X86::MOV8rm,
07408                                                X86::LCMPXCHG8, X86::MOV8rr,
07409                                                X86::NOT8r, X86::AL,
07410                                                X86::GR8RegisterClass);
07411   case X86::ATOMXOR8:
07412     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
07413                                                X86::XOR8ri, X86::MOV8rm,
07414                                                X86::LCMPXCHG8, X86::MOV8rr,
07415                                                X86::NOT8r, X86::AL,
07416                                                X86::GR8RegisterClass);
07417   case X86::ATOMNAND8:
07418     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
07419                                                X86::AND8ri, X86::MOV8rm,
07420                                                X86::LCMPXCHG8, X86::MOV8rr,
07421                                                X86::NOT8r, X86::AL,
07422                                                X86::GR8RegisterClass, true);
07423   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
07424   // This group is for 64-bit host.
07425   case X86::ATOMAND64:
07426     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
07427                                                X86::AND64ri32, X86::MOV64rm, 
07428                                                X86::LCMPXCHG64, X86::MOV64rr,
07429                                                X86::NOT64r, X86::RAX,
07430                                                X86::GR64RegisterClass);
07431   case X86::ATOMOR64:
07432     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 
07433                                                X86::OR64ri32, X86::MOV64rm, 
07434                                                X86::LCMPXCHG64, X86::MOV64rr,
07435                                                X86::NOT64r, X86::RAX,
07436                                                X86::GR64RegisterClass);
07437   case X86::ATOMXOR64:
07438     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
07439                                                X86::XOR64ri32, X86::MOV64rm, 
07440                                                X86::LCMPXCHG64, X86::MOV64rr,
07441                                                X86::NOT64r, X86::RAX,
07442                                                X86::GR64RegisterClass);
07443   case X86::ATOMNAND64:
07444     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
07445                                                X86::AND64ri32, X86::MOV64rm,
07446                                                X86::LCMPXCHG64, X86::MOV64rr,
07447                                                X86::NOT64r, X86::RAX,
07448                                                X86::GR64RegisterClass, true);
07449   case X86::ATOMMIN64:
07450     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
07451   case X86::ATOMMAX64:
07452     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
07453   case X86::ATOMUMIN64:
07454     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
07455   case X86::ATOMUMAX64:
07456     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
07457 
07458   // This group does 64-bit operations on a 32-bit host.
07459   case X86::ATOMAND6432:
07460     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
07461                                                X86::AND32rr, X86::AND32rr,
07462                                                X86::AND32ri, X86::AND32ri,
07463                                                false);
07464   case X86::ATOMOR6432:
07465     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
07466                                                X86::OR32rr, X86::OR32rr,
07467                                                X86::OR32ri, X86::OR32ri,
07468                                                false);
07469   case X86::ATOMXOR6432:
07470     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
07471                                                X86::XOR32rr, X86::XOR32rr,
07472                                                X86::XOR32ri, X86::XOR32ri,
07473                                                false);
07474   case X86::ATOMNAND6432:
07475     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
07476                                                X86::AND32rr, X86::AND32rr,
07477                                                X86::AND32ri, X86::AND32ri,
07478                                                true);
07479   case X86::ATOMADD6432:
07480     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
07481                                                X86::ADD32rr, X86::ADC32rr,
07482                                                X86::ADD32ri, X86::ADC32ri,
07483                                                false);
07484   case X86::ATOMSUB6432:
07485     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
07486                                                X86::SUB32rr, X86::SBB32rr,
07487                                                X86::SUB32ri, X86::SBB32ri,
07488                                                false);
07489   case X86::ATOMSWAP6432:
07490     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
07491                                                X86::MOV32rr, X86::MOV32rr,
07492                                                X86::MOV32ri, X86::MOV32ri,
07493                                                false);
07494   }
07495 }
07496 
07497 //===----------------------------------------------------------------------===//
07498 //                           X86 Optimization Hooks
07499 //===----------------------------------------------------------------------===//
07500 
07501 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
07502                                                        const APInt &Mask,
07503                                                        APInt &KnownZero,
07504                                                        APInt &KnownOne,
07505                                                        const SelectionDAG &DAG,
07506                                                        unsigned Depth) const {
07507   unsigned Opc = Op.getOpcode();
07508   assert((Opc >= ISD::BUILTIN_OP_END ||
07509           Opc == ISD::INTRINSIC_WO_CHAIN ||
07510           Opc == ISD::INTRINSIC_W_CHAIN ||
07511           Opc == ISD::INTRINSIC_VOID) &&
07512          "Should use MaskedValueIsZero if you don't know whether Op"
07513          " is a target node!");
07514 
07515   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
07516   switch (Opc) {
07517   default: break;
07518   case X86ISD::ADD:
07519   case X86ISD::SUB:
07520   case X86ISD::SMUL:
07521   case X86ISD::UMUL:
07522     // These nodes' second result is a boolean.
07523     if (Op.getResNo() == 0)
07524       break;
07525     // Fallthrough
07526   case X86ISD::SETCC:
07527     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
07528                                        Mask.getBitWidth() - 1);
07529     break;
07530   }
07531 }
07532 
07533 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
07534 /// node is a GlobalAddress + offset.
07535 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
07536                                        GlobalValue* &GA, int64_t &Offset) const{
07537   if (N->getOpcode() == X86ISD::Wrapper) {
07538     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
07539       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
07540       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
07541       return true;
07542     }
07543   }
07544   return TargetLowering::isGAPlusOffset(N, GA, Offset);
07545 }
07546 
07547 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
07548                                const TargetLowering &TLI) {
07549   GlobalValue *GV;
07550   int64_t Offset = 0;
07551   if (TLI.isGAPlusOffset(Base, GV, Offset))
07552     return (GV->getAlignment() >= N && (Offset % N) == 0);
07553   // DAG combine handles the stack object case.
07554   return false;
07555 }
07556 
07557 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
07558                                      unsigned NumElems, MVT EVT,
07559                                      SDNode *&Base,
07560                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
07561                                      const TargetLowering &TLI) {
07562   Base = NULL;
07563   for (unsigned i = 0; i < NumElems; ++i) {
07564     SDValue Idx = PermMask.getOperand(i);
07565     if (Idx.getOpcode() == ISD::UNDEF) {
07566       if (!Base)
07567         return false;
07568       continue;
07569     }
07570 
07571     SDValue Elt = DAG.getShuffleScalarElt(N, i);
07572     if (!Elt.getNode() ||
07573         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
07574       return false;
07575     if (!Base) {
07576       Base = Elt.getNode();
07577       if (Base->getOpcode() == ISD::UNDEF)
07578         return false;
07579       continue;
07580     }
07581     if (Elt.getOpcode() == ISD::UNDEF)
07582       continue;
07583 
07584     if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
07585                                EVT.getSizeInBits()/8, i, MFI))
07586       return false;
07587   }
07588   return true;
07589 }
07590 
07591 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
07592 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
07593 /// if the load addresses are consecutive, non-overlapping, and in the right
07594 /// order.
07595 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
07596                                        const TargetLowering &TLI) {
07597   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
07598   MVT VT = N->getValueType(0);
07599   MVT EVT = VT.getVectorElementType();
07600   SDValue PermMask = N->getOperand(2);
07601   unsigned NumElems = PermMask.getNumOperands();
07602   SDNode *Base = NULL;
07603   if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
07604                                 DAG, MFI, TLI))
07605     return SDValue();
07606 
07607   LoadSDNode *LD = cast<LoadSDNode>(Base);
07608   if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
07609     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
07610                        LD->getSrcValueOffset(), LD->isVolatile());
07611   return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
07612                      LD->getSrcValueOffset(), LD->isVolatile(),
07613                      LD->getAlignment());
07614 }
07615 
07616 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
07617 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
07618                                          TargetLowering::DAGCombinerInfo &DCI,
07619                                          const X86Subtarget *Subtarget,
07620                                          const TargetLowering &TLI) {
07621   unsigned NumOps = N->getNumOperands();
07622 
07623   // Ignore single operand BUILD_VECTOR.
07624   if (NumOps == 1)
07625     return SDValue();
07626 
07627   MVT VT = N->getValueType(0);
07628   MVT EVT = VT.getVectorElementType();
07629   if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
07630     // We are looking for load i64 and zero extend. We want to transform
07631     // it before legalizer has a chance to expand it. Also look for i64
07632     // BUILD_PAIR bit casted to f64.
07633     return SDValue();
07634   // This must be an insertion into a zero vector.
07635   SDValue HighElt = N->getOperand(1);
07636   if (!isZeroNode(HighElt))
07637     return SDValue();
07638 
07639   // Value must be a load.
07640   SDNode *Base = N->getOperand(0).getNode();
07641   if (!isa<LoadSDNode>(Base)) {
07642     if (Base->getOpcode() != ISD::BIT_CONVERT)
07643       return SDValue();
07644     Base = Base->getOperand(0).getNode();
07645     if (!isa<LoadSDNode>(Base))
07646       return SDValue();
07647   }
07648 
07649   // Transform it into VZEXT_LOAD addr.
07650   LoadSDNode *LD = cast<LoadSDNode>(Base);
07651   
07652   // Load must not be an extload.
07653   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
07654     return SDValue();
07655 
07656   // Load type should legal type so we don't have to legalize it.
07657   if (!TLI.isTypeLegal(VT))
07658     return SDValue();
07659 
07660   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
07661   SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
07662   SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, Tys, Ops, 2);
07663   TargetLowering::TargetLoweringOpt TLO(DAG);
07664   TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
07665   DCI.CommitTargetLoweringOpt(TLO);
07666   return ResNode;
07667 }                                           
07668 
07669 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
07670 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
07671                                       const X86Subtarget *Subtarget) {
07672   SDValue Cond = N->getOperand(0);
07673 
07674   // If we have SSE[12] support, try to form min/max nodes.
07675   if (Subtarget->hasSSE2() &&
07676       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
07677     if (Cond.getOpcode() == ISD::SETCC) {
07678       // Get the LHS/RHS of the select.
07679       SDValue LHS = N->getOperand(1);
07680       SDValue RHS = N->getOperand(2);
07681       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
07682 
07683       unsigned Opcode = 0;
07684       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
07685         switch (CC) {
07686         default: break;
07687         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
07688         case ISD::SETULE:
07689         case ISD::SETLE:
07690           if (!UnsafeFPMath) break;
07691           // FALL THROUGH.
07692         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
07693         case ISD::SETLT:
07694           Opcode = X86ISD::FMIN;
07695           break;
07696 
07697         case ISD::SETOGT: // (X > Y) ? X : Y -> max
07698         case ISD::SETUGT:
07699         case ISD::SETGT:
07700           if (!UnsafeFPMath) break;
07701           // FALL THROUGH.
07702         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
07703         case ISD::SETGE:
07704           Opcode = X86ISD::FMAX;
07705           break;
07706         }
07707       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
07708         switch (CC) {
07709         default: break;
07710         case ISD::SETOGT: // (X > Y) ? Y : X -> min
07711         case ISD::SETUGT:
07712         case ISD::SETGT:
07713           if (!UnsafeFPMath) break;
07714           // FALL THROUGH.
07715         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
07716         case ISD::SETGE:
07717           Opcode = X86ISD::FMIN;
07718           break;
07719 
07720         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
07721         case ISD::SETULE:
07722         case ISD::SETLE:
07723           if (!UnsafeFPMath) break;
07724           // FALL THROUGH.
07725         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
07726         case ISD::SETLT:
07727           Opcode = X86ISD::FMAX;
07728           break;
07729         }
07730       }
07731 
07732       if (Opcode)
07733         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
07734     }
07735 
07736   }
07737 
07738   return SDValue();
07739 }
07740 
07741 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
07742 ///                       when possible.
07743 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
07744                                    const X86Subtarget *Subtarget) {
07745   // On X86 with SSE2 support, we can transform this to a vector shift if
07746   // all elements are shifted by the same amount.  We can't do this in legalize
07747   // because the a constant vector is typically transformed to a constant pool
07748   // so we have no knowledge of the shift amount.
07749   if (!Subtarget->hasSSE2())
07750     return SDValue();
07751     
07752   MVT VT = N->getValueType(0);
07753   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
07754     return SDValue();
07755     
07756   SDValue ShAmtOp = N->getOperand(1);
07757   MVT EltVT = VT.getVectorElementType();
07758   SDValue BaseShAmt;
07759   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
07760     unsigned NumElts = VT.getVectorNumElements();
07761     unsigned i = 0;
07762     for (; i != NumElts; ++i) {
07763       SDValue Arg = ShAmtOp.getOperand(i);
07764       if (Arg.getOpcode() == ISD::UNDEF) continue;
07765       BaseShAmt = Arg;
07766       break;
07767     }
07768     for (; i != NumElts; ++i) {
07769       SDValue Arg = ShAmtOp.getOperand(i);
07770       if (Arg.getOpcode() == ISD::UNDEF) continue;
07771       if (Arg != BaseShAmt) {
07772         return SDValue();
07773       }
07774     }
07775   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
07776              isSplatMask(ShAmtOp.getOperand(2).getNode())) {
07777       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, ShAmtOp,
07778                               DAG.getIntPtrConstant(0));
07779   } else
07780     return SDValue();
07781 
07782   if (EltVT.bitsGT(MVT::i32))
07783     BaseShAmt = DAG.getNode(ISD::TRUNCATE, MVT::i32, BaseShAmt);
07784   else if (EltVT.bitsLT(MVT::i32))
07785     BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, BaseShAmt);
07786 
07787   // The shift amount is identical so we can do a vector shift.
07788   SDValue  ValOp = N->getOperand(0);
07789   switch (N->getOpcode()) {
07790   default:
07791     assert(0 && "Unknown shift opcode!");
07792     break;
07793   case ISD::SHL:
07794     if (VT == MVT::v2i64)
07795       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
07796                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
07797                          ValOp, BaseShAmt);
07798     if (VT == MVT::v4i32)
07799       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
07800                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
07801                          ValOp, BaseShAmt);
07802     if (VT == MVT::v8i16)
07803       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
07804                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
07805                          ValOp, BaseShAmt);
07806     break;
07807   case ISD::SRA:
07808     if (VT == MVT::v4i32)
07809       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
07810                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
07811                          ValOp, BaseShAmt);
07812     if (VT == MVT::v8i16)
07813       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
07814                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
07815                          ValOp, BaseShAmt);
07816     break;
07817   case ISD::SRL:
07818     if (VT == MVT::v2i64)
07819       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
07820                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
07821                          ValOp, BaseShAmt);
07822     if (VT == MVT::v4i32)
07823       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
07824                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
07825                          ValOp, BaseShAmt);
07826     if (VT ==  MVT::v8i16)
07827       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
07828                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
07829                          ValOp, BaseShAmt);
07830     break;
07831   }
07832   return SDValue();
07833 }
07834 
07835 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
07836 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
07837                                      const X86Subtarget *Subtarget) {
07838   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
07839   // the FP state in cases where an emms may be missing.
07840   // A preferable solution to the general problem is to figure out the right
07841   // places to insert EMMS.  This qualifies as a quick hack.
07842   StoreSDNode *St = cast<StoreSDNode>(N);
07843   if (St->getValue().getValueType().isVector() &&
07844       St->getValue().getValueType().getSizeInBits() == 64 &&
07845       isa<LoadSDNode>(St->getValue()) &&
07846       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
07847       St->getChain().hasOneUse() && !St->isVolatile()) {
07848     SDNode* LdVal = St->getValue().getNode();
07849     LoadSDNode *Ld = 0;
07850     int TokenFactorIndex = -1;
07851     SmallVector<SDValue, 8> Ops;
07852     SDNode* ChainVal = St->getChain().getNode();
07853     // Must be a store of a load.  We currently handle two cases:  the load
07854     // is a direct child, and it's under an intervening TokenFactor.  It is
07855     // possible to dig deeper under nested TokenFactors.
07856     if (ChainVal == LdVal)
07857       Ld = cast<LoadSDNode>(St->getChain());
07858     else if (St->getValue().hasOneUse() &&
07859              ChainVal->getOpcode() == ISD::TokenFactor) {
07860       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
07861         if (ChainVal->getOperand(i).getNode() == LdVal) {
07862           TokenFactorIndex = i;
07863           Ld = cast<LoadSDNode>(St->getValue());
07864         } else
07865           Ops.push_back(ChainVal->getOperand(i));
07866       }
07867     }
07868     if (Ld) {
07869       // If we are a 64-bit capable x86, lower to a single movq load/store pair.
07870       if (Subtarget->is64Bit()) {
07871         SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(), 
07872                                       Ld->getBasePtr(), Ld->getSrcValue(), 
07873                                       Ld->getSrcValueOffset(), Ld->isVolatile(),
07874                                       Ld->getAlignment());
07875         SDValue NewChain = NewLd.getValue(1);
07876         if (TokenFactorIndex != -1) {
07877           Ops.push_back(NewChain);
07878           NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
07879                                  Ops.size());
07880         }
07881         return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
07882                             St->getSrcValue(), St->getSrcValueOffset(),
07883                             St->isVolatile(), St->getAlignment());
07884       }
07885 
07886       // Otherwise, lower to two 32-bit copies.
07887       SDValue LoAddr = Ld->getBasePtr();
07888       SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
07889                                      DAG.getConstant(4, MVT::i32));
07890 
07891       SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
07892                                    Ld->getSrcValue(), Ld->getSrcValueOffset(),
07893                                    Ld->isVolatile(), Ld->getAlignment());
07894       SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
07895                                    Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
07896                                    Ld->isVolatile(), 
07897                                    MinAlign(Ld->getAlignment(), 4));
07898 
07899       SDValue NewChain = LoLd.getValue(1);
07900       if (TokenFactorIndex != -1) {
07901         Ops.push_back(LoLd);
07902         Ops.push_back(HiLd);
07903         NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
07904                                Ops.size());
07905       }
07906 
07907       LoAddr = St->getBasePtr();
07908       HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
07909                            DAG.getConstant(4, MVT::i32));
07910 
07911       SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
07912                           St->getSrcValue(), St->getSrcValueOffset(),
07913                           St->isVolatile(), St->getAlignment());
07914       SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
07915                                     St->getSrcValue(),
07916                                     St->getSrcValueOffset() + 4,
07917                                     St->isVolatile(), 
07918                                     MinAlign(St->getAlignment(), 4));
07919       return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
07920     }
07921   }
07922   return SDValue();
07923 }
07924 
07925 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
07926 /// X86ISD::FXOR nodes.
07927 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
07928   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
07929   // F[X]OR(0.0, x) -> x
07930   // F[X]OR(x, 0.0) -> x
07931   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
07932     if (C->getValueAPF().isPosZero())
07933       return N->getOperand(1);
07934   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
07935     if (C->getValueAPF().isPosZero())
07936       return N->getOperand(0);
07937   return SDValue();
07938 }
07939 
07940 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
07941 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
07942   // FAND(0.0, x) -> 0.0
07943   // FAND(x, 0.0) -> 0.0
07944   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
07945     if (C->getValueAPF().isPosZero())
07946       return N->getOperand(0);
07947   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
07948     if (C->getValueAPF().isPosZero())
07949       return N->getOperand(1);
07950   return SDValue();
07951 }
07952 
07953 static SDValue PerformBTCombine(SDNode *N,
07954                                 SelectionDAG &DAG,
07955                                 TargetLowering::DAGCombinerInfo &DCI) {
07956   // BT ignores high bits in the bit index operand.
07957   SDValue Op1 = N->getOperand(1);
07958   if (Op1.hasOneUse()) {
07959     unsigned BitWidth = Op1.getValueSizeInBits();
07960     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
07961     APInt KnownZero, KnownOne;
07962     TargetLowering::TargetLoweringOpt TLO(DAG);
07963     TargetLowering &TLI = DAG.getTargetLoweringInfo();
07964     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
07965         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
07966       DCI.CommitTargetLoweringOpt(TLO);
07967   }
07968   return SDValue();
07969 }
07970 
07971 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
07972                                              DAGCombinerInfo &DCI) const {
07973   SelectionDAG &DAG = DCI.DAG;
07974   switch (N->getOpcode()) {
07975   default: break;
07976   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
07977   case ISD::BUILD_VECTOR:
07978     return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
07979   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
07980   case ISD::SHL:
07981   case ISD::SRA:
07982   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
07983   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
07984   case X86ISD::FXOR:
07985   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
07986   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
07987   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
07988   }
07989 
07990   return SDValue();
07991 }
07992 
07993 //===----------------------------------------------------------------------===//
07994 //                           X86 Inline Assembly Support
07995 //===----------------------------------------------------------------------===//
07996 
07997 /// getConstraintType - Given a constraint letter, return the type of
07998 /// constraint it is for this target.
07999 X86TargetLowering::ConstraintType
08000 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
08001   if (Constraint.size() == 1) {
08002     switch (Constraint[0]) {
08003     case 'A':
08004       return C_Register;
08005     case 'f':
08006     case 'r':
08007     case 'R':
08008     case 'l':
08009     case 'q':
08010     case 'Q':
08011     case 'x':
08012     case 'y':
08013     case 'Y':
08014       return C_RegisterClass;
08015     default:
08016       break;
08017     }
08018   }
08019   return TargetLowering::getConstraintType(Constraint);
08020 }
08021 
08022 /// LowerXConstraint - try to replace an X constraint, which matches anything,
08023 /// with another that has more specific requirements based on the type of the
08024 /// corresponding operand.
08025 const char *X86TargetLowering::
08026 LowerXConstraint(MVT ConstraintVT) const {
08027   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
08028   // 'f' like normal targets.
08029   if (ConstraintVT.isFloatingPoint()) {
08030     if (Subtarget->hasSSE2())
08031       return "Y";
08032     if (Subtarget->hasSSE1())
08033       return "x";
08034   }
08035   
08036   return TargetLowering::LowerXConstraint(ConstraintVT);
08037 }
08038 
08039 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
08040 /// vector.  If it is invalid, don't add anything to Ops.
08041 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
08042                                                      char Constraint,
08043                                                      bool hasMemory,
08044                                                      std::vector<SDValue>&Ops,
08045                                                      SelectionDAG &DAG) const {
08046   SDValue Result(0, 0);
08047   
08048   switch (Constraint) {
08049   default: break;
08050   case 'I':
08051     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
08052       if (C->getZExtValue() <= 31) {
08053         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
08054         break;
08055       }
08056     }
08057     return;
08058   case 'J':
08059     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
08060       if (C->getZExtValue() <= 63) {
08061         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
08062         break;
08063       }
08064     }
08065     return;
08066   case 'N':
08067     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
08068       if (C->getZExtValue() <= 255) {
08069         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
08070         break;
08071       }
08072     }
08073     return;
08074   case 'i': {
08075     // Literal immediates are always ok.
08076     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
08077       Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
08078       break;
08079     }
08080 
08081     // If we are in non-pic codegen mode, we allow the address of a global (with
08082     // an optional displacement) to be used with 'i'.
08083     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
08084     int64_t Offset = 0;
08085     
08086     // Match either (GA) or (GA+C)
08087     if (GA) {
08088       Offset = GA->getOffset();
08089     } else if (Op.getOpcode() == ISD::ADD) {
08090       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
08091       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
08092       if (C && GA) {
08093         Offset = GA->getOffset()+C->getZExtValue();
08094       } else {
08095         C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
08096         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
08097         if (C && GA)
08098           Offset = GA->getOffset()+C->getZExtValue();
08099         else
08100           C = 0, GA = 0;
08101       }
08102     }
08103     
08104     if (GA) {
08105       if (hasMemory) 
08106         Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
08107       else
08108         Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
08109                                         Offset);
08110       Result = Op;
08111       break;
08112     }
08113 
08114     // Otherwise, not valid for this mode.
08115     return;
08116   }
08117   }
08118   
08119   if (Result.getNode()) {
08120     Ops.push_back(Result);
08121     return;
08122   }
08123   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
08124                                                       Ops, DAG);
08125 }
08126 
08127 std::vector<unsigned> X86TargetLowering::
08128 getRegClassForInlineAsmConstraint(const std::string &Constraint,
08129                                   MVT VT) const {
08130   if (Constraint.size() == 1) {
08131     // FIXME: not handling fp-stack yet!
08132     switch (Constraint[0]) {      // GCC X86 Constraint Letters
08133     default: break;  // Unknown constraint letter
08134     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
08135     case 'Q':   // Q_REGS
08136       if (VT == MVT::i32)
08137         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
08138       else if (VT == MVT::i16)
08139         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
08140       else if (VT == MVT::i8)
08141         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
08142       else if (VT == MVT::i64)
08143         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
08144       break;
08145     }
08146   }
08147 
08148   return std::vector<unsigned>();
08149 }
08150 
08151 std::pair<unsigned, const TargetRegisterClass*>
08152 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
08153                                                 MVT VT) const {
08154   // First, see if this is a constraint that directly corresponds to an LLVM
08155   // register class.
08156   if (Constraint.size() == 1) {
08157     // GCC Constraint Letters
08158     switch (Constraint[0]) {
08159     default: break;
08160     case 'r':   // GENERAL_REGS
08161     case 'R':   // LEGACY_REGS
08162     case 'l':   // INDEX_REGS
08163       if (VT == MVT::i8)
08164         return std::make_pair(0U, X86::GR8RegisterClass);
08165       if (VT == MVT::i16)
08166         return std::make_pair(0U, X86::GR16RegisterClass);
08167       if (VT == MVT::i32 || !Subtarget->is64Bit())
08168         return std::make_pair(0U, X86::GR32RegisterClass);  
08169       return std::make_pair(0U, X86::GR64RegisterClass);
08170     case 'f':  // FP Stack registers.
08171       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
08172       // value to the correct fpstack register class.
08173       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
08174         return std::make_pair(0U, X86::RFP32RegisterClass);
08175       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
08176         return std::make_pair(0U, X86::RFP64RegisterClass);
08177       return std::make_pair(0U, X86::RFP80RegisterClass);
08178     case 'y':   // MMX_REGS if MMX allowed.
08179       if (!Subtarget->hasMMX()) break;
08180       return std::make_pair(0U, X86::VR64RegisterClass);
08181     case 'Y':   // SSE_REGS if SSE2 allowed
08182       if (!Subtarget->hasSSE2()) break;
08183       // FALL THROUGH.
08184     case 'x':   // SSE_REGS if SSE1 allowed
08185       if (!Subtarget->hasSSE1()) break;
08186 
08187       switch (VT.getSimpleVT()) {
08188       default: break;
08189       // Scalar SSE types.
08190       case MVT::f32:
08191       case MVT::i32:
08192         return std::make_pair(0U, X86::FR32RegisterClass);
08193       case MVT::f64:
08194       case MVT::i64:
08195         return std::make_pair(0U, X86::FR64RegisterClass);
08196       // Vector types.
08197       case MVT::v16i8:
08198       case MVT::v8i16:
08199       case MVT::v4i32:
08200       case MVT::v2i64:
08201       case MVT::v4f32:
08202       case MVT::v2f64:
08203         return std::make_pair(0U, X86::VR128RegisterClass);
08204       }
08205       break;
08206     }
08207   }
08208   
08209   // Use the default implementation in TargetLowering to convert the register
08210   // constraint into a member of a register class.
08211   std::pair<unsigned, const TargetRegisterClass*> Res;
08212   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
08213 
08214   // Not found as a standard register?
08215   if (Res.second == 0) {
08216     // GCC calls "st(0)" just plain "st".
08217     if (StringsEqualNoCase("{st}", Constraint)) {
08218       Res.first = X86::ST0;
08219       Res.second = X86::RFP80RegisterClass;
08220     }
08221     // 'A' means EAX + EDX.
08222     if (Constraint == "A") {
08223       Res.first = X86::EAX;
08224       Res.second = X86::GRADRegisterClass;
08225     }
08226     return Res;
08227   }
08228 
08229   // Otherwise, check to see if this is a register class of the wrong value
08230   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
08231   // turn into {ax},{dx}.
08232   if (Res.second->hasType(VT))
08233     return Res;   // Correct type already, nothing to do.
08234 
08235   // All of the single-register GCC register classes map their values onto
08236   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
08237   // really want an 8-bit or 32-bit register, map to the appropriate register
08238   // class and return the appropriate register.
08239   if (Res.second == X86::GR16RegisterClass) {
08240     if (VT == MVT::i8) {
08241       unsigned DestReg = 0;
08242       switch (Res.first) {
08243       default: break;
08244       case X86::AX: DestReg = X86::AL; break;
08245       case X86::DX: DestReg = X86::DL; break;
08246       case X86::CX: DestReg = X86::CL; break;
08247       case X86::BX: DestReg = X86::BL; break;
08248       }
08249       if (DestReg) {
08250         Res.first = DestReg;
08251         Res.second = Res.second = X86::GR8RegisterClass;
08252       }
08253     } else if (VT == MVT::i32) {
08254       unsigned DestReg = 0;
08255       switch (Res.first) {
08256       default: break;
08257       case X86::AX: DestReg = X86::EAX; break;
08258       case X86::DX: DestReg = X86::EDX; break;
08259       case X86::CX: DestReg = X86::ECX; break;
08260       case X86::BX: DestReg = X86::EBX; break;
08261       case X86::SI: DestReg = X86::ESI; break;
08262       case X86::DI: DestReg = X86::EDI; break;
08263       case X86::BP: DestReg = X86::EBP; break;
08264       case X86::SP: DestReg = X86::ESP; break;
08265       }
08266       if (DestReg) {
08267         Res.first = DestReg;
08268         Res.second = Res.second = X86::GR32RegisterClass;
08269       }
08270     } else if (VT == MVT::i64) {
08271       unsigned DestReg = 0;
08272       switch (Res.first) {
08273       default: break;
08274       case X86::AX: DestReg = X86::RAX; break;
08275       case X86::DX: DestReg = X86::RDX; break;
08276       case X86::CX: DestReg = X86::RCX; break;
08277       case X86::BX: DestReg = X86::RBX; break;
08278       case X86::SI: DestReg = X86::RSI; break;
08279       case X86::DI: DestReg = X86::RDI; break;
08280       case X86::BP: DestReg = X86::RBP; break;
08281       case X86::SP: DestReg = X86::RSP; break;
08282       }
08283       if (DestReg) {
08284         Res.first = DestReg;
08285         Res.second = Res.second = X86::GR64RegisterClass;
08286       }
08287     }
08288   } else if (Res.second == X86::FR32RegisterClass ||
08289              Res.second == X86::FR64RegisterClass ||
08290              Res.second == X86::VR128RegisterClass) {
08291     // Handle references to XMM physical registers that got mapped into the
08292     // wrong class.  This can happen with constraints like {xmm0} where the
08293     // target independent register mapper will just pick the first match it can
08294     // find, ignoring the required type.
08295     if (VT == MVT::f32)
08296       Res.second = X86::FR32RegisterClass;
08297     else if (VT == MVT::f64)
08298       Res.second = X86::FR64RegisterClass;
08299     else if (X86::VR128RegisterClass->hasType(VT))
08300       Res.second = X86::VR128RegisterClass;
08301   }
08302 
08303   return Res;
08304 }
08305 
08306 //===----------------------------------------------------------------------===//
08307 //                           X86 Widen vector type
08308 //===----------------------------------------------------------------------===//
08309 
08310 /// getWidenVectorType: given a vector type, returns the type to widen
08311 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
08312 /// If there is no vector type that we want to widen to, returns MVT::Other
08313 /// When and where to widen is target dependent based on the cost of
08314 /// scalarizing vs using the wider vector type.
08315 
08316 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
08317   assert(VT.isVector());
08318   if (isTypeLegal(VT))
08319     return VT;
08320   
08321   // TODO: In computeRegisterProperty, we can compute the list of legal vector
08322   //       type based on element type.  This would speed up our search (though
08323   //       it may not be worth it since the size of the list is relatively
08324   //       small).
08325   MVT EltVT = VT.getVectorElementType();
08326   unsigned NElts = VT.getVectorNumElements();
08327   
08328   // On X86, it make sense to widen any vector wider than 1
08329   if (NElts <= 1)
08330     return MVT::Other;
08331   
08332   for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE; 
08333        nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
08334     MVT SVT = (MVT::SimpleValueType)nVT;
08335     
08336     if (isTypeLegal(SVT) && 
08337         SVT.getVectorElementType() == EltVT && 
08338         SVT.getVectorNumElements() > NElts)
08339       return SVT;
08340   }
08341   return MVT::Other;
08342 }