Home | History | Annotate | Download | only in X86
      1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file defines the X86-specific support for the FastISel class. Much
     11 // of the target-specific code is generated by tablegen in the file
     12 // X86GenFastISel.inc, which is #included here.
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #include "X86.h"
     17 #include "X86InstrBuilder.h"
     18 #include "X86ISelLowering.h"
     19 #include "X86RegisterInfo.h"
     20 #include "X86Subtarget.h"
     21 #include "X86TargetMachine.h"
     22 #include "llvm/CallingConv.h"
     23 #include "llvm/DerivedTypes.h"
     24 #include "llvm/GlobalVariable.h"
     25 #include "llvm/GlobalAlias.h"
     26 #include "llvm/Instructions.h"
     27 #include "llvm/IntrinsicInst.h"
     28 #include "llvm/Operator.h"
     29 #include "llvm/CodeGen/Analysis.h"
     30 #include "llvm/CodeGen/FastISel.h"
     31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
     32 #include "llvm/CodeGen/MachineConstantPool.h"
     33 #include "llvm/CodeGen/MachineFrameInfo.h"
     34 #include "llvm/CodeGen/MachineRegisterInfo.h"
     35 #include "llvm/Support/CallSite.h"
     36 #include "llvm/Support/ErrorHandling.h"
     37 #include "llvm/Support/GetElementPtrTypeIterator.h"
     38 #include "llvm/Target/TargetOptions.h"
     39 using namespace llvm;
     40 
     41 namespace {
     42 
     43 class X86FastISel : public FastISel {
     44   /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
     45   /// make the right decision when generating code for different targets.
     46   const X86Subtarget *Subtarget;
     47 
     48   /// StackPtr - Register used as the stack pointer.
     49   ///
     50   unsigned StackPtr;
     51 
     52   /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
     53   /// floating point ops.
     54   /// When SSE is available, use it for f32 operations.
     55   /// When SSE2 is available, use it for f64 operations.
     56   bool X86ScalarSSEf64;
     57   bool X86ScalarSSEf32;
     58 
     59 public:
     60   explicit X86FastISel(FunctionLoweringInfo &funcInfo) : FastISel(funcInfo) {
     61     Subtarget = &TM.getSubtarget<X86Subtarget>();
     62     StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
     63     X86ScalarSSEf64 = Subtarget->hasSSE2();
     64     X86ScalarSSEf32 = Subtarget->hasSSE1();
     65   }
     66 
     67   virtual bool TargetSelectInstruction(const Instruction *I);
     68 
     69   /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
     70   /// vreg is being provided by the specified load instruction.  If possible,
     71   /// try to fold the load as an operand to the instruction, returning true if
     72   /// possible.
     73   virtual bool TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
     74                              const LoadInst *LI);
     75 
     76 #include "X86GenFastISel.inc"
     77 
     78 private:
     79   bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
     80 
     81   bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
     82 
     83   bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM);
     84   bool X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM);
     85 
     86   bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
     87                          unsigned &ResultReg);
     88 
     89   bool X86SelectAddress(const Value *V, X86AddressMode &AM);
     90   bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
     91 
     92   bool X86SelectLoad(const Instruction *I);
     93 
     94   bool X86SelectStore(const Instruction *I);
     95 
     96   bool X86SelectRet(const Instruction *I);
     97 
     98   bool X86SelectCmp(const Instruction *I);
     99 
    100   bool X86SelectZExt(const Instruction *I);
    101 
    102   bool X86SelectBranch(const Instruction *I);
    103 
    104   bool X86SelectShift(const Instruction *I);
    105 
    106   bool X86SelectSelect(const Instruction *I);
    107 
    108   bool X86SelectTrunc(const Instruction *I);
    109 
    110   bool X86SelectFPExt(const Instruction *I);
    111   bool X86SelectFPTrunc(const Instruction *I);
    112 
    113   bool X86VisitIntrinsicCall(const IntrinsicInst &I);
    114   bool X86SelectCall(const Instruction *I);
    115 
    116   bool DoSelectCall(const Instruction *I, const char *MemIntName);
    117 
    118   const X86InstrInfo *getInstrInfo() const {
    119     return getTargetMachine()->getInstrInfo();
    120   }
    121   const X86TargetMachine *getTargetMachine() const {
    122     return static_cast<const X86TargetMachine *>(&TM);
    123   }
    124 
    125   unsigned TargetMaterializeConstant(const Constant *C);
    126 
    127   unsigned TargetMaterializeAlloca(const AllocaInst *C);
    128 
    129   unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
    130 
    131   /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
    132   /// computed in an SSE register, not on the X87 floating point stack.
    133   bool isScalarFPTypeInSSEReg(EVT VT) const {
    134     return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
    135       (VT == MVT::f32 && X86ScalarSSEf32);   // f32 is when SSE1
    136   }
    137 
    138   bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
    139 
    140   bool IsMemcpySmall(uint64_t Len);
    141 
    142   bool TryEmitSmallMemcpy(X86AddressMode DestAM,
    143                           X86AddressMode SrcAM, uint64_t Len);
    144 };
    145 
    146 } // end anonymous namespace.
    147 
    148 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
    149   EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
    150   if (evt == MVT::Other || !evt.isSimple())
    151     // Unhandled type. Halt "fast" selection and bail.
    152     return false;
    153 
    154   VT = evt.getSimpleVT();
    155   // For now, require SSE/SSE2 for performing floating-point operations,
    156   // since x87 requires additional work.
    157   if (VT == MVT::f64 && !X86ScalarSSEf64)
    158      return false;
    159   if (VT == MVT::f32 && !X86ScalarSSEf32)
    160      return false;
    161   // Similarly, no f80 support yet.
    162   if (VT == MVT::f80)
    163     return false;
    164   // We only handle legal types. For example, on x86-32 the instruction
    165   // selector contains all of the 64-bit instructions from x86-64,
    166   // under the assumption that i64 won't be used if the target doesn't
    167   // support it.
    168   return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
    169 }
    170 
    171 #include "X86GenCallingConv.inc"
    172 
    173 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
    174 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
    175 /// Return true and the result register by reference if it is possible.
    176 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
    177                                   unsigned &ResultReg) {
    178   // Get opcode and regclass of the output for the given load instruction.
    179   unsigned Opc = 0;
    180   const TargetRegisterClass *RC = NULL;
    181   switch (VT.getSimpleVT().SimpleTy) {
    182   default: return false;
    183   case MVT::i1:
    184   case MVT::i8:
    185     Opc = X86::MOV8rm;
    186     RC  = X86::GR8RegisterClass;
    187     break;
    188   case MVT::i16:
    189     Opc = X86::MOV16rm;
    190     RC  = X86::GR16RegisterClass;
    191     break;
    192   case MVT::i32:
    193     Opc = X86::MOV32rm;
    194     RC  = X86::GR32RegisterClass;
    195     break;
    196   case MVT::i64:
    197     // Must be in x86-64 mode.
    198     Opc = X86::MOV64rm;
    199     RC  = X86::GR64RegisterClass;
    200     break;
    201   case MVT::f32:
    202     if (X86ScalarSSEf32) {
    203       Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
    204       RC  = X86::FR32RegisterClass;
    205     } else {
    206       Opc = X86::LD_Fp32m;
    207       RC  = X86::RFP32RegisterClass;
    208     }
    209     break;
    210   case MVT::f64:
    211     if (X86ScalarSSEf64) {
    212       Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
    213       RC  = X86::FR64RegisterClass;
    214     } else {
    215       Opc = X86::LD_Fp64m;
    216       RC  = X86::RFP64RegisterClass;
    217     }
    218     break;
    219   case MVT::f80:
    220     // No f80 support yet.
    221     return false;
    222   }
    223 
    224   ResultReg = createResultReg(RC);
    225   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
    226                          DL, TII.get(Opc), ResultReg), AM);
    227   return true;
    228 }
    229 
    230 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
    231 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
    232 /// and a displacement offset, or a GlobalAddress,
    233 /// i.e. V. Return true if it is possible.
    234 bool
    235 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM) {
    236   // Get opcode and regclass of the output for the given store instruction.
    237   unsigned Opc = 0;
    238   switch (VT.getSimpleVT().SimpleTy) {
    239   case MVT::f80: // No f80 support yet.
    240   default: return false;
    241   case MVT::i1: {
    242     // Mask out all but lowest bit.
    243     unsigned AndResult = createResultReg(X86::GR8RegisterClass);
    244     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
    245             TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
    246     Val = AndResult;
    247   }
    248   // FALLTHROUGH, handling i1 as i8.
    249   case MVT::i8:  Opc = X86::MOV8mr;  break;
    250   case MVT::i16: Opc = X86::MOV16mr; break;
    251   case MVT::i32: Opc = X86::MOV32mr; break;
    252   case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
    253   case MVT::f32:
    254     Opc = X86ScalarSSEf32 ?
    255           (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
    256     break;
    257   case MVT::f64:
    258     Opc = X86ScalarSSEf64 ?
    259           (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
    260     break;
    261   case MVT::v4f32:
    262     Opc = X86::MOVAPSmr;
    263     break;
    264   case MVT::v2f64:
    265     Opc = X86::MOVAPDmr;
    266     break;
    267   case MVT::v4i32:
    268   case MVT::v2i64:
    269   case MVT::v8i16:
    270   case MVT::v16i8:
    271     Opc = X86::MOVDQAmr;
    272     break;
    273   }
    274 
    275   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
    276                          DL, TII.get(Opc)), AM).addReg(Val);
    277   return true;
    278 }
    279 
    280 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
    281                                    const X86AddressMode &AM) {
    282   // Handle 'null' like i32/i64 0.
    283   if (isa<ConstantPointerNull>(Val))
    284     Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
    285 
    286   // If this is a store of a simple constant, fold the constant into the store.
    287   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
    288     unsigned Opc = 0;
    289     bool Signed = true;
    290     switch (VT.getSimpleVT().SimpleTy) {
    291     default: break;
    292     case MVT::i1:  Signed = false;     // FALLTHROUGH to handle as i8.
    293     case MVT::i8:  Opc = X86::MOV8mi;  break;
    294     case MVT::i16: Opc = X86::MOV16mi; break;
    295     case MVT::i32: Opc = X86::MOV32mi; break;
    296     case MVT::i64:
    297       // Must be a 32-bit sign extended value.
    298       if ((int)CI->getSExtValue() == CI->getSExtValue())
    299         Opc = X86::MOV64mi32;
    300       break;
    301     }
    302 
    303     if (Opc) {
    304       addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
    305                              DL, TII.get(Opc)), AM)
    306                              .addImm(Signed ? (uint64_t) CI->getSExtValue() :
    307                                               CI->getZExtValue());
    308       return true;
    309     }
    310   }
    311 
    312   unsigned ValReg = getRegForValue(Val);
    313   if (ValReg == 0)
    314     return false;
    315 
    316   return X86FastEmitStore(VT, ValReg, AM);
    317 }
    318 
    319 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
    320 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
    321 /// ISD::SIGN_EXTEND).
    322 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
    323                                     unsigned Src, EVT SrcVT,
    324                                     unsigned &ResultReg) {
    325   unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
    326                            Src, /*TODO: Kill=*/false);
    327 
    328   if (RR != 0) {
    329     ResultReg = RR;
    330     return true;
    331   } else
    332     return false;
    333 }
    334 
    335 /// X86SelectAddress - Attempt to fill in an address from the given value.
    336 ///
    337 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
    338   const User *U = NULL;
    339   unsigned Opcode = Instruction::UserOp1;
    340   if (const Instruction *I = dyn_cast<Instruction>(V)) {
    341     // Don't walk into other basic blocks; it's possible we haven't
    342     // visited them yet, so the instructions may not yet be assigned
    343     // virtual registers.
    344     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
    345         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
    346       Opcode = I->getOpcode();
    347       U = I;
    348     }
    349   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
    350     Opcode = C->getOpcode();
    351     U = C;
    352   }
    353 
    354   if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
    355     if (Ty->getAddressSpace() > 255)
    356       // Fast instruction selection doesn't support the special
    357       // address spaces.
    358       return false;
    359 
    360   switch (Opcode) {
    361   default: break;
    362   case Instruction::BitCast:
    363     // Look past bitcasts.
    364     return X86SelectAddress(U->getOperand(0), AM);
    365 
    366   case Instruction::IntToPtr:
    367     // Look past no-op inttoptrs.
    368     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
    369       return X86SelectAddress(U->getOperand(0), AM);
    370     break;
    371 
    372   case Instruction::PtrToInt:
    373     // Look past no-op ptrtoints.
    374     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
    375       return X86SelectAddress(U->getOperand(0), AM);
    376     break;
    377 
    378   case Instruction::Alloca: {
    379     // Do static allocas.
    380     const AllocaInst *A = cast<AllocaInst>(V);
    381     DenseMap<const AllocaInst*, int>::iterator SI =
    382       FuncInfo.StaticAllocaMap.find(A);
    383     if (SI != FuncInfo.StaticAllocaMap.end()) {
    384       AM.BaseType = X86AddressMode::FrameIndexBase;
    385       AM.Base.FrameIndex = SI->second;
    386       return true;
    387     }
    388     break;
    389   }
    390 
    391   case Instruction::Add: {
    392     // Adds of constants are common and easy enough.
    393     if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
    394       uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
    395       // They have to fit in the 32-bit signed displacement field though.
    396       if (isInt<32>(Disp)) {
    397         AM.Disp = (uint32_t)Disp;
    398         return X86SelectAddress(U->getOperand(0), AM);
    399       }
    400     }
    401     break;
    402   }
    403 
    404   case Instruction::GetElementPtr: {
    405     X86AddressMode SavedAM = AM;
    406 
    407     // Pattern-match simple GEPs.
    408     uint64_t Disp = (int32_t)AM.Disp;
    409     unsigned IndexReg = AM.IndexReg;
    410     unsigned Scale = AM.Scale;
    411     gep_type_iterator GTI = gep_type_begin(U);
    412     // Iterate through the indices, folding what we can. Constants can be
    413     // folded, and one dynamic index can be handled, if the scale is supported.
    414     for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
    415          i != e; ++i, ++GTI) {
    416       const Value *Op = *i;
    417       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
    418         const StructLayout *SL = TD.getStructLayout(STy);
    419         Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
    420         continue;
    421       }
    422 
    423       // A array/variable index is always of the form i*S where S is the
    424       // constant scale size.  See if we can push the scale into immediates.
    425       uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
    426       for (;;) {
    427         if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
    428           // Constant-offset addressing.
    429           Disp += CI->getSExtValue() * S;
    430           break;
    431         }
    432         if (isa<AddOperator>(Op) &&
    433             (!isa<Instruction>(Op) ||
    434              FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
    435                == FuncInfo.MBB) &&
    436             isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
    437           // An add (in the same block) with a constant operand. Fold the
    438           // constant.
    439           ConstantInt *CI =
    440             cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
    441           Disp += CI->getSExtValue() * S;
    442           // Iterate on the other operand.
    443           Op = cast<AddOperator>(Op)->getOperand(0);
    444           continue;
    445         }
    446         if (IndexReg == 0 &&
    447             (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
    448             (S == 1 || S == 2 || S == 4 || S == 8)) {
    449           // Scaled-index addressing.
    450           Scale = S;
    451           IndexReg = getRegForGEPIndex(Op).first;
    452           if (IndexReg == 0)
    453             return false;
    454           break;
    455         }
    456         // Unsupported.
    457         goto unsupported_gep;
    458       }
    459     }
    460     // Check for displacement overflow.
    461     if (!isInt<32>(Disp))
    462       break;
    463     // Ok, the GEP indices were covered by constant-offset and scaled-index
    464     // addressing. Update the address state and move on to examining the base.
    465     AM.IndexReg = IndexReg;
    466     AM.Scale = Scale;
    467     AM.Disp = (uint32_t)Disp;
    468     if (X86SelectAddress(U->getOperand(0), AM))
    469       return true;
    470 
    471     // If we couldn't merge the gep value into this addr mode, revert back to
    472     // our address and just match the value instead of completely failing.
    473     AM = SavedAM;
    474     break;
    475   unsupported_gep:
    476     // Ok, the GEP indices weren't all covered.
    477     break;
    478   }
    479   }
    480 
    481   // Handle constant address.
    482   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
    483     // Can't handle alternate code models yet.
    484     if (TM.getCodeModel() != CodeModel::Small)
    485       return false;
    486 
    487     // Can't handle TLS yet.
    488     if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
    489       if (GVar->isThreadLocal())
    490         return false;
    491 
    492     // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how
    493     // it works...).
    494     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
    495       if (const GlobalVariable *GVar =
    496             dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)))
    497         if (GVar->isThreadLocal())
    498           return false;
    499 
    500     // RIP-relative addresses can't have additional register operands, so if
    501     // we've already folded stuff into the addressing mode, just force the
    502     // global value into its own register, which we can use as the basereg.
    503     if (!Subtarget->isPICStyleRIPRel() ||
    504         (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
    505       // Okay, we've committed to selecting this global. Set up the address.
    506       AM.GV = GV;
    507 
    508       // Allow the subtarget to classify the global.
    509       unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
    510 
    511       // If this reference is relative to the pic base, set it now.
    512       if (isGlobalRelativeToPICBase(GVFlags)) {
    513         // FIXME: How do we know Base.Reg is free??
    514         AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
    515       }
    516 
    517       // Unless the ABI requires an extra load, return a direct reference to
    518       // the global.
    519       if (!isGlobalStubReference(GVFlags)) {
    520         if (Subtarget->isPICStyleRIPRel()) {
    521           // Use rip-relative addressing if we can.  Above we verified that the
    522           // base and index registers are unused.
    523           assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
    524           AM.Base.Reg = X86::RIP;
    525         }
    526         AM.GVOpFlags = GVFlags;
    527         return true;
    528       }
    529 
    530       // Ok, we need to do a load from a stub.  If we've already loaded from
    531       // this stub, reuse the loaded pointer, otherwise emit the load now.
    532       DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
    533       unsigned LoadReg;
    534       if (I != LocalValueMap.end() && I->second != 0) {
    535         LoadReg = I->second;
    536       } else {
    537         // Issue load from stub.
    538         unsigned Opc = 0;
    539         const TargetRegisterClass *RC = NULL;
    540         X86AddressMode StubAM;
    541         StubAM.Base.Reg = AM.Base.Reg;
    542         StubAM.GV = GV;
    543         StubAM.GVOpFlags = GVFlags;
    544 
    545         // Prepare for inserting code in the local-value area.
    546         SavePoint SaveInsertPt = enterLocalValueArea();
    547 
    548         if (TLI.getPointerTy() == MVT::i64) {
    549           Opc = X86::MOV64rm;
    550           RC  = X86::GR64RegisterClass;
    551 
    552           if (Subtarget->isPICStyleRIPRel())
    553             StubAM.Base.Reg = X86::RIP;
    554         } else {
    555           Opc = X86::MOV32rm;
    556           RC  = X86::GR32RegisterClass;
    557         }
    558 
    559         LoadReg = createResultReg(RC);
    560         MachineInstrBuilder LoadMI =
    561           BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
    562         addFullAddress(LoadMI, StubAM);
    563 
    564         // Ok, back to normal mode.
    565         leaveLocalValueArea(SaveInsertPt);
    566 
    567         // Prevent loading GV stub multiple times in same MBB.
    568         LocalValueMap[V] = LoadReg;
    569       }
    570 
    571       // Now construct the final address. Note that the Disp, Scale,
    572       // and Index values may already be set here.
    573       AM.Base.Reg = LoadReg;
    574       AM.GV = 0;
    575       return true;
    576     }
    577   }
    578 
    579   // If all else fails, try to materialize the value in a register.
    580   if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
    581     if (AM.Base.Reg == 0) {
    582       AM.Base.Reg = getRegForValue(V);
    583       return AM.Base.Reg != 0;
    584     }
    585     if (AM.IndexReg == 0) {
    586       assert(AM.Scale == 1 && "Scale with no index!");
    587       AM.IndexReg = getRegForValue(V);
    588       return AM.IndexReg != 0;
    589     }
    590   }
    591 
    592   return false;
    593 }
    594 
    595 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
    596 ///
    597 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
    598   const User *U = NULL;
    599   unsigned Opcode = Instruction::UserOp1;
    600   if (const Instruction *I = dyn_cast<Instruction>(V)) {
    601     Opcode = I->getOpcode();
    602     U = I;
    603   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
    604     Opcode = C->getOpcode();
    605     U = C;
    606   }
    607 
    608   switch (Opcode) {
    609   default: break;
    610   case Instruction::BitCast:
    611     // Look past bitcasts.
    612     return X86SelectCallAddress(U->getOperand(0), AM);
    613 
    614   case Instruction::IntToPtr:
    615     // Look past no-op inttoptrs.
    616     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
    617       return X86SelectCallAddress(U->getOperand(0), AM);
    618     break;
    619 
    620   case Instruction::PtrToInt:
    621     // Look past no-op ptrtoints.
    622     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
    623       return X86SelectCallAddress(U->getOperand(0), AM);
    624     break;
    625   }
    626 
    627   // Handle constant address.
    628   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
    629     // Can't handle alternate code models yet.
    630     if (TM.getCodeModel() != CodeModel::Small)
    631       return false;
    632 
    633     // RIP-relative addresses can't have additional register operands.
    634     if (Subtarget->isPICStyleRIPRel() &&
    635         (AM.Base.Reg != 0 || AM.IndexReg != 0))
    636       return false;
    637 
    638     // Can't handle DLLImport.
    639     if (GV->hasDLLImportLinkage())
    640       return false;
    641 
    642     // Can't handle TLS.
    643     if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
    644       if (GVar->isThreadLocal())
    645         return false;
    646 
    647     // Okay, we've committed to selecting this global. Set up the basic address.
    648     AM.GV = GV;
    649 
    650     // No ABI requires an extra load for anything other than DLLImport, which
    651     // we rejected above. Return a direct reference to the global.
    652     if (Subtarget->isPICStyleRIPRel()) {
    653       // Use rip-relative addressing if we can.  Above we verified that the
    654       // base and index registers are unused.
    655       assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
    656       AM.Base.Reg = X86::RIP;
    657     } else if (Subtarget->isPICStyleStubPIC()) {
    658       AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
    659     } else if (Subtarget->isPICStyleGOT()) {
    660       AM.GVOpFlags = X86II::MO_GOTOFF;
    661     }
    662 
    663     return true;
    664   }
    665 
    666   // If all else fails, try to materialize the value in a register.
    667   if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
    668     if (AM.Base.Reg == 0) {
    669       AM.Base.Reg = getRegForValue(V);
    670       return AM.Base.Reg != 0;
    671     }
    672     if (AM.IndexReg == 0) {
    673       assert(AM.Scale == 1 && "Scale with no index!");
    674       AM.IndexReg = getRegForValue(V);
    675       return AM.IndexReg != 0;
    676     }
    677   }
    678 
    679   return false;
    680 }
    681 
    682 
    683 /// X86SelectStore - Select and emit code to implement store instructions.
    684 bool X86FastISel::X86SelectStore(const Instruction *I) {
    685   // Atomic stores need special handling.
    686   const StoreInst *S = cast<StoreInst>(I);
    687 
    688   if (S->isAtomic())
    689     return false;
    690 
    691   unsigned SABIAlignment =
    692     TD.getABITypeAlignment(S->getValueOperand()->getType());
    693   if (S->getAlignment() != 0 && S->getAlignment() < SABIAlignment)
    694     return false;
    695 
    696   MVT VT;
    697   if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
    698     return false;
    699 
    700   X86AddressMode AM;
    701   if (!X86SelectAddress(I->getOperand(1), AM))
    702     return false;
    703 
    704   return X86FastEmitStore(VT, I->getOperand(0), AM);
    705 }
    706 
    707 /// X86SelectRet - Select and emit code to implement ret instructions.
    708 bool X86FastISel::X86SelectRet(const Instruction *I) {
    709   const ReturnInst *Ret = cast<ReturnInst>(I);
    710   const Function &F = *I->getParent()->getParent();
    711 
    712   if (!FuncInfo.CanLowerReturn)
    713     return false;
    714 
    715   CallingConv::ID CC = F.getCallingConv();
    716   if (CC != CallingConv::C &&
    717       CC != CallingConv::Fast &&
    718       CC != CallingConv::X86_FastCall)
    719     return false;
    720 
    721   if (Subtarget->isTargetWin64())
    722     return false;
    723 
    724   // Don't handle popping bytes on return for now.
    725   if (FuncInfo.MF->getInfo<X86MachineFunctionInfo>()
    726         ->getBytesToPopOnReturn() != 0)
    727     return 0;
    728 
    729   // fastcc with -tailcallopt is intended to provide a guaranteed
    730   // tail call optimization. Fastisel doesn't know how to do that.
    731   if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
    732     return false;
    733 
    734   // Let SDISel handle vararg functions.
    735   if (F.isVarArg())
    736     return false;
    737 
    738   if (Ret->getNumOperands() > 0) {
    739     SmallVector<ISD::OutputArg, 4> Outs;
    740     GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
    741                   Outs, TLI);
    742 
    743     // Analyze operands of the call, assigning locations to each operand.
    744     SmallVector<CCValAssign, 16> ValLocs;
    745     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
    746 		   I->getContext());
    747     CCInfo.AnalyzeReturn(Outs, RetCC_X86);
    748 
    749     const Value *RV = Ret->getOperand(0);
    750     unsigned Reg = getRegForValue(RV);
    751     if (Reg == 0)
    752       return false;
    753 
    754     // Only handle a single return value for now.
    755     if (ValLocs.size() != 1)
    756       return false;
    757 
    758     CCValAssign &VA = ValLocs[0];
    759 
    760     // Don't bother handling odd stuff for now.
    761     if (VA.getLocInfo() != CCValAssign::Full)
    762       return false;
    763     // Only handle register returns for now.
    764     if (!VA.isRegLoc())
    765       return false;
    766 
    767     // The calling-convention tables for x87 returns don't tell
    768     // the whole story.
    769     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
    770       return false;
    771 
    772     unsigned SrcReg = Reg + VA.getValNo();
    773     EVT SrcVT = TLI.getValueType(RV->getType());
    774     EVT DstVT = VA.getValVT();
    775     // Special handling for extended integers.
    776     if (SrcVT != DstVT) {
    777       if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
    778         return false;
    779 
    780       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
    781         return false;
    782 
    783       assert(DstVT == MVT::i32 && "X86 should always ext to i32");
    784 
    785       if (SrcVT == MVT::i1) {
    786         if (Outs[0].Flags.isSExt())
    787           return false;
    788         SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
    789         SrcVT = MVT::i8;
    790       }
    791       unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
    792                                              ISD::SIGN_EXTEND;
    793       SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
    794                           SrcReg, /*TODO: Kill=*/false);
    795     }
    796 
    797     // Make the copy.
    798     unsigned DstReg = VA.getLocReg();
    799     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
    800     // Avoid a cross-class copy. This is very unlikely.
    801     if (!SrcRC->contains(DstReg))
    802       return false;
    803     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
    804             DstReg).addReg(SrcReg);
    805 
    806     // Mark the register as live out of the function.
    807     MRI.addLiveOut(VA.getLocReg());
    808   }
    809 
    810   // Now emit the RET.
    811   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
    812   return true;
    813 }
    814 
    815 /// X86SelectLoad - Select and emit code to implement load instructions.
    816 ///
    817 bool X86FastISel::X86SelectLoad(const Instruction *I)  {
    818   // Atomic loads need special handling.
    819   if (cast<LoadInst>(I)->isAtomic())
    820     return false;
    821 
    822   MVT VT;
    823   if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
    824     return false;
    825 
    826   X86AddressMode AM;
    827   if (!X86SelectAddress(I->getOperand(0), AM))
    828     return false;
    829 
    830   unsigned ResultReg = 0;
    831   if (X86FastEmitLoad(VT, AM, ResultReg)) {
    832     UpdateValueMap(I, ResultReg);
    833     return true;
    834   }
    835   return false;
    836 }
    837 
    838 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
    839   bool HasAVX = Subtarget->hasAVX();
    840   bool X86ScalarSSEf32 = Subtarget->hasSSE1();
    841   bool X86ScalarSSEf64 = Subtarget->hasSSE2();
    842 
    843   switch (VT.getSimpleVT().SimpleTy) {
    844   default:       return 0;
    845   case MVT::i8:  return X86::CMP8rr;
    846   case MVT::i16: return X86::CMP16rr;
    847   case MVT::i32: return X86::CMP32rr;
    848   case MVT::i64: return X86::CMP64rr;
    849   case MVT::f32:
    850     return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
    851   case MVT::f64:
    852     return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
    853   }
    854 }
    855 
    856 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
    857 /// of the comparison, return an opcode that works for the compare (e.g.
    858 /// CMP32ri) otherwise return 0.
    859 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
    860   switch (VT.getSimpleVT().SimpleTy) {
    861   // Otherwise, we can't fold the immediate into this comparison.
    862   default: return 0;
    863   case MVT::i8: return X86::CMP8ri;
    864   case MVT::i16: return X86::CMP16ri;
    865   case MVT::i32: return X86::CMP32ri;
    866   case MVT::i64:
    867     // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
    868     // field.
    869     if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
    870       return X86::CMP64ri32;
    871     return 0;
    872   }
    873 }
    874 
    875 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
    876                                      EVT VT) {
    877   unsigned Op0Reg = getRegForValue(Op0);
    878   if (Op0Reg == 0) return false;
    879 
    880   // Handle 'null' like i32/i64 0.
    881   if (isa<ConstantPointerNull>(Op1))
    882     Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
    883 
    884   // We have two options: compare with register or immediate.  If the RHS of
    885   // the compare is an immediate that we can fold into this compare, use
    886   // CMPri, otherwise use CMPrr.
    887   if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
    888     if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
    889       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
    890         .addReg(Op0Reg)
    891         .addImm(Op1C->getSExtValue());
    892       return true;
    893     }
    894   }
    895 
    896   unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
    897   if (CompareOpc == 0) return false;
    898 
    899   unsigned Op1Reg = getRegForValue(Op1);
    900   if (Op1Reg == 0) return false;
    901   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
    902     .addReg(Op0Reg)
    903     .addReg(Op1Reg);
    904 
    905   return true;
    906 }
    907 
    908 bool X86FastISel::X86SelectCmp(const Instruction *I) {
    909   const CmpInst *CI = cast<CmpInst>(I);
    910 
    911   MVT VT;
    912   if (!isTypeLegal(I->getOperand(0)->getType(), VT))
    913     return false;
    914 
    915   unsigned ResultReg = createResultReg(&X86::GR8RegClass);
    916   unsigned SetCCOpc;
    917   bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
    918   switch (CI->getPredicate()) {
    919   case CmpInst::FCMP_OEQ: {
    920     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
    921       return false;
    922 
    923     unsigned EReg = createResultReg(&X86::GR8RegClass);
    924     unsigned NPReg = createResultReg(&X86::GR8RegClass);
    925     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
    926     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
    927             TII.get(X86::SETNPr), NPReg);
    928     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
    929             TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
    930     UpdateValueMap(I, ResultReg);
    931     return true;
    932   }
    933   case CmpInst::FCMP_UNE: {
    934     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
    935       return false;
    936 
    937     unsigned NEReg = createResultReg(&X86::GR8RegClass);
    938     unsigned PReg = createResultReg(&X86::GR8RegClass);
    939     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
    940     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
    941     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
    942       .addReg(PReg).addReg(NEReg);
    943     UpdateValueMap(I, ResultReg);
    944     return true;
    945   }
    946   case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
    947   case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
    948   case CmpInst::FCMP_OLT: SwapArgs = true;  SetCCOpc = X86::SETAr;  break;
    949   case CmpInst::FCMP_OLE: SwapArgs = true;  SetCCOpc = X86::SETAEr; break;
    950   case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
    951   case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
    952   case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr;  break;
    953   case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr;  break;
    954   case CmpInst::FCMP_UGT: SwapArgs = true;  SetCCOpc = X86::SETBr;  break;
    955   case CmpInst::FCMP_UGE: SwapArgs = true;  SetCCOpc = X86::SETBEr; break;
    956   case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
    957   case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
    958 
    959   case CmpInst::ICMP_EQ:  SwapArgs = false; SetCCOpc = X86::SETEr;  break;
    960   case CmpInst::ICMP_NE:  SwapArgs = false; SetCCOpc = X86::SETNEr; break;
    961   case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
    962   case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
    963   case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
    964   case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
    965   case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr;  break;
    966   case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
    967   case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr;  break;
    968   case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
    969   default:
    970     return false;
    971   }
    972 
    973   const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
    974   if (SwapArgs)
    975     std::swap(Op0, Op1);
    976 
    977   // Emit a compare of Op0/Op1.
    978   if (!X86FastEmitCompare(Op0, Op1, VT))
    979     return false;
    980 
    981   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
    982   UpdateValueMap(I, ResultReg);
    983   return true;
    984 }
    985 
    986 bool X86FastISel::X86SelectZExt(const Instruction *I) {
    987   // Handle zero-extension from i1 to i8, which is common.
    988   if (!I->getOperand(0)->getType()->isIntegerTy(1))
    989     return false;
    990 
    991   EVT DstVT = TLI.getValueType(I->getType());
    992   if (!TLI.isTypeLegal(DstVT))
    993     return false;
    994 
    995   unsigned ResultReg = getRegForValue(I->getOperand(0));
    996   if (ResultReg == 0)
    997     return false;
    998 
    999   // Set the high bits to zero.
   1000   ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
   1001   if (ResultReg == 0)
   1002     return false;
   1003 
   1004   if (DstVT != MVT::i8) {
   1005     ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
   1006                            ResultReg, /*Kill=*/true);
   1007     if (ResultReg == 0)
   1008       return false;
   1009   }
   1010 
   1011   UpdateValueMap(I, ResultReg);
   1012   return true;
   1013 }
   1014 
   1015 
   1016 bool X86FastISel::X86SelectBranch(const Instruction *I) {
   1017   // Unconditional branches are selected by tablegen-generated code.
   1018   // Handle a conditional branch.
   1019   const BranchInst *BI = cast<BranchInst>(I);
   1020   MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
   1021   MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
   1022 
   1023   // Fold the common case of a conditional branch with a comparison
   1024   // in the same block (values defined on other blocks may not have
   1025   // initialized registers).
   1026   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
   1027     if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
   1028       EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
   1029 
   1030       // Try to take advantage of fallthrough opportunities.
   1031       CmpInst::Predicate Predicate = CI->getPredicate();
   1032       if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
   1033         std::swap(TrueMBB, FalseMBB);
   1034         Predicate = CmpInst::getInversePredicate(Predicate);
   1035       }
   1036 
   1037       bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
   1038       unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
   1039 
   1040       switch (Predicate) {
   1041       case CmpInst::FCMP_OEQ:
   1042         std::swap(TrueMBB, FalseMBB);
   1043         Predicate = CmpInst::FCMP_UNE;
   1044         // FALL THROUGH
   1045       case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
   1046       case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4;  break;
   1047       case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
   1048       case CmpInst::FCMP_OLT: SwapArgs = true;  BranchOpc = X86::JA_4;  break;
   1049       case CmpInst::FCMP_OLE: SwapArgs = true;  BranchOpc = X86::JAE_4; break;
   1050       case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
   1051       case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
   1052       case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4;  break;
   1053       case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4;  break;
   1054       case CmpInst::FCMP_UGT: SwapArgs = true;  BranchOpc = X86::JB_4;  break;
   1055       case CmpInst::FCMP_UGE: SwapArgs = true;  BranchOpc = X86::JBE_4; break;
   1056       case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4;  break;
   1057       case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
   1058 
   1059       case CmpInst::ICMP_EQ:  SwapArgs = false; BranchOpc = X86::JE_4;  break;
   1060       case CmpInst::ICMP_NE:  SwapArgs = false; BranchOpc = X86::JNE_4; break;
   1061       case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4;  break;
   1062       case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
   1063       case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4;  break;
   1064       case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
   1065       case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4;  break;
   1066       case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
   1067       case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4;  break;
   1068       case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
   1069       default:
   1070         return false;
   1071       }
   1072 
   1073       const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
   1074       if (SwapArgs)
   1075         std::swap(Op0, Op1);
   1076 
   1077       // Emit a compare of the LHS and RHS, setting the flags.
   1078       if (!X86FastEmitCompare(Op0, Op1, VT))
   1079         return false;
   1080 
   1081       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
   1082         .addMBB(TrueMBB);
   1083 
   1084       if (Predicate == CmpInst::FCMP_UNE) {
   1085         // X86 requires a second branch to handle UNE (and OEQ,
   1086         // which is mapped to UNE above).
   1087         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
   1088           .addMBB(TrueMBB);
   1089       }
   1090 
   1091       FastEmitBranch(FalseMBB, DL);
   1092       FuncInfo.MBB->addSuccessor(TrueMBB);
   1093       return true;
   1094     }
   1095   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
   1096     // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
   1097     // typically happen for _Bool and C++ bools.
   1098     MVT SourceVT;
   1099     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
   1100         isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
   1101       unsigned TestOpc = 0;
   1102       switch (SourceVT.SimpleTy) {
   1103       default: break;
   1104       case MVT::i8:  TestOpc = X86::TEST8ri; break;
   1105       case MVT::i16: TestOpc = X86::TEST16ri; break;
   1106       case MVT::i32: TestOpc = X86::TEST32ri; break;
   1107       case MVT::i64: TestOpc = X86::TEST64ri32; break;
   1108       }
   1109       if (TestOpc) {
   1110         unsigned OpReg = getRegForValue(TI->getOperand(0));
   1111         if (OpReg == 0) return false;
   1112         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
   1113           .addReg(OpReg).addImm(1);
   1114 
   1115         unsigned JmpOpc = X86::JNE_4;
   1116         if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
   1117           std::swap(TrueMBB, FalseMBB);
   1118           JmpOpc = X86::JE_4;
   1119         }
   1120 
   1121         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
   1122           .addMBB(TrueMBB);
   1123         FastEmitBranch(FalseMBB, DL);
   1124         FuncInfo.MBB->addSuccessor(TrueMBB);
   1125         return true;
   1126       }
   1127     }
   1128   }
   1129 
   1130   // Otherwise do a clumsy setcc and re-test it.
   1131   // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
   1132   // in an explicit cast, so make sure to handle that correctly.
   1133   unsigned OpReg = getRegForValue(BI->getCondition());
   1134   if (OpReg == 0) return false;
   1135 
   1136   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
   1137     .addReg(OpReg).addImm(1);
   1138   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
   1139     .addMBB(TrueMBB);
   1140   FastEmitBranch(FalseMBB, DL);
   1141   FuncInfo.MBB->addSuccessor(TrueMBB);
   1142   return true;
   1143 }
   1144 
   1145 bool X86FastISel::X86SelectShift(const Instruction *I) {
   1146   unsigned CReg = 0, OpReg = 0;
   1147   const TargetRegisterClass *RC = NULL;
   1148   if (I->getType()->isIntegerTy(8)) {
   1149     CReg = X86::CL;
   1150     RC = &X86::GR8RegClass;
   1151     switch (I->getOpcode()) {
   1152     case Instruction::LShr: OpReg = X86::SHR8rCL; break;
   1153     case Instruction::AShr: OpReg = X86::SAR8rCL; break;
   1154     case Instruction::Shl:  OpReg = X86::SHL8rCL; break;
   1155     default: return false;
   1156     }
   1157   } else if (I->getType()->isIntegerTy(16)) {
   1158     CReg = X86::CX;
   1159     RC = &X86::GR16RegClass;
   1160     switch (I->getOpcode()) {
   1161     case Instruction::LShr: OpReg = X86::SHR16rCL; break;
   1162     case Instruction::AShr: OpReg = X86::SAR16rCL; break;
   1163     case Instruction::Shl:  OpReg = X86::SHL16rCL; break;
   1164     default: return false;
   1165     }
   1166   } else if (I->getType()->isIntegerTy(32)) {
   1167     CReg = X86::ECX;
   1168     RC = &X86::GR32RegClass;
   1169     switch (I->getOpcode()) {
   1170     case Instruction::LShr: OpReg = X86::SHR32rCL; break;
   1171     case Instruction::AShr: OpReg = X86::SAR32rCL; break;
   1172     case Instruction::Shl:  OpReg = X86::SHL32rCL; break;
   1173     default: return false;
   1174     }
   1175   } else if (I->getType()->isIntegerTy(64)) {
   1176     CReg = X86::RCX;
   1177     RC = &X86::GR64RegClass;
   1178     switch (I->getOpcode()) {
   1179     case Instruction::LShr: OpReg = X86::SHR64rCL; break;
   1180     case Instruction::AShr: OpReg = X86::SAR64rCL; break;
   1181     case Instruction::Shl:  OpReg = X86::SHL64rCL; break;
   1182     default: return false;
   1183     }
   1184   } else {
   1185     return false;
   1186   }
   1187 
   1188   MVT VT;
   1189   if (!isTypeLegal(I->getType(), VT))
   1190     return false;
   1191 
   1192   unsigned Op0Reg = getRegForValue(I->getOperand(0));
   1193   if (Op0Reg == 0) return false;
   1194 
   1195   unsigned Op1Reg = getRegForValue(I->getOperand(1));
   1196   if (Op1Reg == 0) return false;
   1197   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
   1198           CReg).addReg(Op1Reg);
   1199 
   1200   // The shift instruction uses X86::CL. If we defined a super-register
   1201   // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
   1202   if (CReg != X86::CL)
   1203     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
   1204             TII.get(TargetOpcode::KILL), X86::CL)
   1205       .addReg(CReg, RegState::Kill);
   1206 
   1207   unsigned ResultReg = createResultReg(RC);
   1208   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
   1209     .addReg(Op0Reg);
   1210   UpdateValueMap(I, ResultReg);
   1211   return true;
   1212 }
   1213 
   1214 bool X86FastISel::X86SelectSelect(const Instruction *I) {
   1215   MVT VT;
   1216   if (!isTypeLegal(I->getType(), VT))
   1217     return false;
   1218 
   1219   // We only use cmov here, if we don't have a cmov instruction bail.
   1220   if (!Subtarget->hasCMov()) return false;
   1221 
   1222   unsigned Opc = 0;
   1223   const TargetRegisterClass *RC = NULL;
   1224   if (VT == MVT::i16) {
   1225     Opc = X86::CMOVE16rr;
   1226     RC = &X86::GR16RegClass;
   1227   } else if (VT == MVT::i32) {
   1228     Opc = X86::CMOVE32rr;
   1229     RC = &X86::GR32RegClass;
   1230   } else if (VT == MVT::i64) {
   1231     Opc = X86::CMOVE64rr;
   1232     RC = &X86::GR64RegClass;
   1233   } else {
   1234     return false;
   1235   }
   1236 
   1237   unsigned Op0Reg = getRegForValue(I->getOperand(0));
   1238   if (Op0Reg == 0) return false;
   1239   unsigned Op1Reg = getRegForValue(I->getOperand(1));
   1240   if (Op1Reg == 0) return false;
   1241   unsigned Op2Reg = getRegForValue(I->getOperand(2));
   1242   if (Op2Reg == 0) return false;
   1243 
   1244   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
   1245     .addReg(Op0Reg).addReg(Op0Reg);
   1246   unsigned ResultReg = createResultReg(RC);
   1247   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
   1248     .addReg(Op1Reg).addReg(Op2Reg);
   1249   UpdateValueMap(I, ResultReg);
   1250   return true;
   1251 }
   1252 
   1253 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
   1254   // fpext from float to double.
   1255   if (X86ScalarSSEf64 &&
   1256       I->getType()->isDoubleTy()) {
   1257     const Value *V = I->getOperand(0);
   1258     if (V->getType()->isFloatTy()) {
   1259       unsigned OpReg = getRegForValue(V);
   1260       if (OpReg == 0) return false;
   1261       unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
   1262       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
   1263               TII.get(X86::CVTSS2SDrr), ResultReg)
   1264         .addReg(OpReg);
   1265       UpdateValueMap(I, ResultReg);
   1266       return true;
   1267     }
   1268   }
   1269 
   1270   return false;
   1271 }
   1272 
   1273 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
   1274   if (X86ScalarSSEf64) {
   1275     if (I->getType()->isFloatTy()) {
   1276       const Value *V = I->getOperand(0);
   1277       if (V->getType()->isDoubleTy()) {
   1278         unsigned OpReg = getRegForValue(V);
   1279         if (OpReg == 0) return false;
   1280         unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
   1281         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
   1282                 TII.get(X86::CVTSD2SSrr), ResultReg)
   1283           .addReg(OpReg);
   1284         UpdateValueMap(I, ResultReg);
   1285         return true;
   1286       }
   1287     }
   1288   }
   1289 
   1290   return false;
   1291 }
   1292 
   1293 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
   1294   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
   1295   EVT DstVT = TLI.getValueType(I->getType());
   1296 
   1297   // This code only handles truncation to byte.
   1298   if (DstVT != MVT::i8 && DstVT != MVT::i1)
   1299     return false;
   1300   if (!TLI.isTypeLegal(SrcVT))
   1301     return false;
   1302 
   1303   unsigned InputReg = getRegForValue(I->getOperand(0));
   1304   if (!InputReg)
   1305     // Unhandled operand.  Halt "fast" selection and bail.
   1306     return false;
   1307 
   1308   if (SrcVT == MVT::i8) {
   1309     // Truncate from i8 to i1; no code needed.
   1310     UpdateValueMap(I, InputReg);
   1311     return true;
   1312   }
   1313 
   1314   if (!Subtarget->is64Bit()) {
   1315     // If we're on x86-32; we can't extract an i8 from a general register.
   1316     // First issue a copy to GR16_ABCD or GR32_ABCD.
   1317     const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
   1318       ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
   1319     unsigned CopyReg = createResultReg(CopyRC);
   1320     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
   1321             CopyReg).addReg(InputReg);
   1322     InputReg = CopyReg;
   1323   }
   1324 
   1325   // Issue an extract_subreg.
   1326   unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
   1327                                                   InputReg, /*Kill=*/true,
   1328                                                   X86::sub_8bit);
   1329   if (!ResultReg)
   1330     return false;
   1331 
   1332   UpdateValueMap(I, ResultReg);
   1333   return true;
   1334 }
   1335 
   1336 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
   1337   return Len <= (Subtarget->is64Bit() ? 32 : 16);
   1338 }
   1339 
   1340 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
   1341                                      X86AddressMode SrcAM, uint64_t Len) {
   1342 
   1343   // Make sure we don't bloat code by inlining very large memcpy's.
   1344   if (!IsMemcpySmall(Len))
   1345     return false;
   1346 
   1347   bool i64Legal = Subtarget->is64Bit();
   1348 
   1349   // We don't care about alignment here since we just emit integer accesses.
   1350   while (Len) {
   1351     MVT VT;
   1352     if (Len >= 8 && i64Legal)
   1353       VT = MVT::i64;
   1354     else if (Len >= 4)
   1355       VT = MVT::i32;
   1356     else if (Len >= 2)
   1357       VT = MVT::i16;
   1358     else {
   1359       assert(Len == 1);
   1360       VT = MVT::i8;
   1361     }
   1362 
   1363     unsigned Reg;
   1364     bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
   1365     RV &= X86FastEmitStore(VT, Reg, DestAM);
   1366     assert(RV && "Failed to emit load or store??");
   1367 
   1368     unsigned Size = VT.getSizeInBits()/8;
   1369     Len -= Size;
   1370     DestAM.Disp += Size;
   1371     SrcAM.Disp += Size;
   1372   }
   1373 
   1374   return true;
   1375 }
   1376 
   1377 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
   1378   // FIXME: Handle more intrinsics.
   1379   switch (I.getIntrinsicID()) {
   1380   default: return false;
   1381   case Intrinsic::memcpy: {
   1382     const MemCpyInst &MCI = cast<MemCpyInst>(I);
   1383     // Don't handle volatile or variable length memcpys.
   1384     if (MCI.isVolatile())
   1385       return false;
   1386 
   1387     if (isa<ConstantInt>(MCI.getLength())) {
   1388       // Small memcpy's are common enough that we want to do them
   1389       // without a call if possible.
   1390       uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
   1391       if (IsMemcpySmall(Len)) {
   1392         X86AddressMode DestAM, SrcAM;
   1393         if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
   1394             !X86SelectAddress(MCI.getRawSource(), SrcAM))
   1395           return false;
   1396         TryEmitSmallMemcpy(DestAM, SrcAM, Len);
   1397         return true;
   1398       }
   1399     }
   1400 
   1401     unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
   1402     if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
   1403       return false;
   1404 
   1405     if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
   1406       return false;
   1407 
   1408     return DoSelectCall(&I, "memcpy");
   1409   }
   1410   case Intrinsic::memset: {
   1411     const MemSetInst &MSI = cast<MemSetInst>(I);
   1412 
   1413     if (MSI.isVolatile())
   1414       return false;
   1415 
   1416     unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
   1417     if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
   1418       return false;
   1419 
   1420     if (MSI.getDestAddressSpace() > 255)
   1421       return false;
   1422 
   1423     return DoSelectCall(&I, "memset");
   1424   }
   1425   case Intrinsic::stackprotector: {
   1426     // Emit code inline code to store the stack guard onto the stack.
   1427     EVT PtrTy = TLI.getPointerTy();
   1428 
   1429     const Value *Op1 = I.getArgOperand(0); // The guard's value.
   1430     const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
   1431 
   1432     // Grab the frame index.
   1433     X86AddressMode AM;
   1434     if (!X86SelectAddress(Slot, AM)) return false;
   1435     if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
   1436     return true;
   1437   }
   1438   case Intrinsic::dbg_declare: {
   1439     const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
   1440     X86AddressMode AM;
   1441     assert(DI->getAddress() && "Null address should be checked earlier!");
   1442     if (!X86SelectAddress(DI->getAddress(), AM))
   1443       return false;
   1444     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
   1445     // FIXME may need to add RegState::Debug to any registers produced,
   1446     // although ESP/EBP should be the only ones at the moment.
   1447     addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
   1448       addImm(0).addMetadata(DI->getVariable());
   1449     return true;
   1450   }
   1451   case Intrinsic::trap: {
   1452     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
   1453     return true;
   1454   }
   1455   case Intrinsic::sadd_with_overflow:
   1456   case Intrinsic::uadd_with_overflow: {
   1457     // FIXME: Should fold immediates.
   1458 
   1459     // Replace "add with overflow" intrinsics with an "add" instruction followed
   1460     // by a seto/setc instruction.
   1461     const Function *Callee = I.getCalledFunction();
   1462     Type *RetTy =
   1463       cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
   1464 
   1465     MVT VT;
   1466     if (!isTypeLegal(RetTy, VT))
   1467       return false;
   1468 
   1469     const Value *Op1 = I.getArgOperand(0);
   1470     const Value *Op2 = I.getArgOperand(1);
   1471     unsigned Reg1 = getRegForValue(Op1);
   1472     unsigned Reg2 = getRegForValue(Op2);
   1473 
   1474     if (Reg1 == 0 || Reg2 == 0)
   1475       // FIXME: Handle values *not* in registers.
   1476       return false;
   1477 
   1478     unsigned OpC = 0;
   1479     if (VT == MVT::i32)
   1480       OpC = X86::ADD32rr;
   1481     else if (VT == MVT::i64)
   1482       OpC = X86::ADD64rr;
   1483     else
   1484       return false;
   1485 
   1486     // The call to CreateRegs builds two sequential registers, to store the
   1487     // both the the returned values.
   1488     unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
   1489     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
   1490       .addReg(Reg1).addReg(Reg2);
   1491 
   1492     unsigned Opc = X86::SETBr;
   1493     if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
   1494       Opc = X86::SETOr;
   1495     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
   1496 
   1497     UpdateValueMap(&I, ResultReg, 2);
   1498     return true;
   1499   }
   1500   }
   1501 }
   1502 
   1503 bool X86FastISel::X86SelectCall(const Instruction *I) {
   1504   const CallInst *CI = cast<CallInst>(I);
   1505   const Value *Callee = CI->getCalledValue();
   1506 
   1507   // Can't handle inline asm yet.
   1508   if (isa<InlineAsm>(Callee))
   1509     return false;
   1510 
   1511   // Handle intrinsic calls.
   1512   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
   1513     return X86VisitIntrinsicCall(*II);
   1514 
   1515   return DoSelectCall(I, 0);
   1516 }
   1517 
   1518 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
   1519 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
   1520   const CallInst *CI = cast<CallInst>(I);
   1521   const Value *Callee = CI->getCalledValue();
   1522 
   1523   // Handle only C and fastcc calling conventions for now.
   1524   ImmutableCallSite CS(CI);
   1525   CallingConv::ID CC = CS.getCallingConv();
   1526   if (CC != CallingConv::C && CC != CallingConv::Fast &&
   1527       CC != CallingConv::X86_FastCall)
   1528     return false;
   1529 
   1530   // fastcc with -tailcallopt is intended to provide a guaranteed
   1531   // tail call optimization. Fastisel doesn't know how to do that.
   1532   if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
   1533     return false;
   1534 
   1535   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
   1536   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
   1537   bool isVarArg = FTy->isVarArg();
   1538 
   1539   // Don't know how to handle Win64 varargs yet.  Nothing special needed for
   1540   // x86-32.  Special handling for x86-64 is implemented.
   1541   if (isVarArg && Subtarget->isTargetWin64())
   1542     return false;
   1543 
   1544   // Fast-isel doesn't know about callee-pop yet.
   1545   if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
   1546                        TM.Options.GuaranteedTailCallOpt))
   1547     return false;
   1548 
   1549   // Check whether the function can return without sret-demotion.
   1550   SmallVector<ISD::OutputArg, 4> Outs;
   1551   SmallVector<uint64_t, 4> Offsets;
   1552   GetReturnInfo(I->getType(), CS.getAttributes().getRetAttributes(),
   1553                 Outs, TLI, &Offsets);
   1554   bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
   1555 					   *FuncInfo.MF, FTy->isVarArg(),
   1556 					   Outs, FTy->getContext());
   1557   if (!CanLowerReturn)
   1558     return false;
   1559 
   1560   // Materialize callee address in a register. FIXME: GV address can be
   1561   // handled with a CALLpcrel32 instead.
   1562   X86AddressMode CalleeAM;
   1563   if (!X86SelectCallAddress(Callee, CalleeAM))
   1564     return false;
   1565   unsigned CalleeOp = 0;
   1566   const GlobalValue *GV = 0;
   1567   if (CalleeAM.GV != 0) {
   1568     GV = CalleeAM.GV;
   1569   } else if (CalleeAM.Base.Reg != 0) {
   1570     CalleeOp = CalleeAM.Base.Reg;
   1571   } else
   1572     return false;
   1573 
   1574   // Deal with call operands first.
   1575   SmallVector<const Value *, 8> ArgVals;
   1576   SmallVector<unsigned, 8> Args;
   1577   SmallVector<MVT, 8> ArgVTs;
   1578   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
   1579   unsigned arg_size = CS.arg_size();
   1580   Args.reserve(arg_size);
   1581   ArgVals.reserve(arg_size);
   1582   ArgVTs.reserve(arg_size);
   1583   ArgFlags.reserve(arg_size);
   1584   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
   1585        i != e; ++i) {
   1586     // If we're lowering a mem intrinsic instead of a regular call, skip the
   1587     // last two arguments, which should not passed to the underlying functions.
   1588     if (MemIntName && e-i <= 2)
   1589       break;
   1590     Value *ArgVal = *i;
   1591     ISD::ArgFlagsTy Flags;
   1592     unsigned AttrInd = i - CS.arg_begin() + 1;
   1593     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
   1594       Flags.setSExt();
   1595     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
   1596       Flags.setZExt();
   1597 
   1598     if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
   1599       PointerType *Ty = cast<PointerType>(ArgVal->getType());
   1600       Type *ElementTy = Ty->getElementType();
   1601       unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
   1602       unsigned FrameAlign = CS.getParamAlignment(AttrInd);
   1603       if (!FrameAlign)
   1604         FrameAlign = TLI.getByValTypeAlignment(ElementTy);
   1605       Flags.setByVal();
   1606       Flags.setByValSize(FrameSize);
   1607       Flags.setByValAlign(FrameAlign);
   1608       if (!IsMemcpySmall(FrameSize))
   1609         return false;
   1610     }
   1611 
   1612     if (CS.paramHasAttr(AttrInd, Attribute::InReg))
   1613       Flags.setInReg();
   1614     if (CS.paramHasAttr(AttrInd, Attribute::Nest))
   1615       Flags.setNest();
   1616 
   1617     // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
   1618     // instruction.  This is safe because it is common to all fastisel supported
   1619     // calling conventions on x86.
   1620     if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
   1621       if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
   1622           CI->getBitWidth() == 16) {
   1623         if (Flags.isSExt())
   1624           ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
   1625         else
   1626           ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
   1627       }
   1628     }
   1629 
   1630     unsigned ArgReg;
   1631 
   1632     // Passing bools around ends up doing a trunc to i1 and passing it.
   1633     // Codegen this as an argument + "and 1".
   1634     if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
   1635         cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
   1636         ArgVal->hasOneUse()) {
   1637       ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
   1638       ArgReg = getRegForValue(ArgVal);
   1639       if (ArgReg == 0) return false;
   1640 
   1641       MVT ArgVT;
   1642       if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
   1643 
   1644       ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
   1645                            ArgVal->hasOneUse(), 1);
   1646     } else {
   1647       ArgReg = getRegForValue(ArgVal);
   1648     }
   1649 
   1650     if (ArgReg == 0) return false;
   1651 
   1652     Type *ArgTy = ArgVal->getType();
   1653     MVT ArgVT;
   1654     if (!isTypeLegal(ArgTy, ArgVT))
   1655       return false;
   1656     if (ArgVT == MVT::x86mmx)
   1657       return false;
   1658     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
   1659     Flags.setOrigAlign(OriginalAlignment);
   1660 
   1661     Args.push_back(ArgReg);
   1662     ArgVals.push_back(ArgVal);
   1663     ArgVTs.push_back(ArgVT);
   1664     ArgFlags.push_back(Flags);
   1665   }
   1666 
   1667   // Analyze operands of the call, assigning locations to each operand.
   1668   SmallVector<CCValAssign, 16> ArgLocs;
   1669   CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
   1670 		 I->getParent()->getContext());
   1671 
   1672   // Allocate shadow area for Win64
   1673   if (Subtarget->isTargetWin64())
   1674     CCInfo.AllocateStack(32, 8);
   1675 
   1676   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
   1677 
   1678   // Get a count of how many bytes are to be pushed on the stack.
   1679   unsigned NumBytes = CCInfo.getNextStackOffset();
   1680 
   1681   // Issue CALLSEQ_START
   1682   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
   1683   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
   1684     .addImm(NumBytes);
   1685 
   1686   // Process argument: walk the register/memloc assignments, inserting
   1687   // copies / loads.
   1688   SmallVector<unsigned, 4> RegArgs;
   1689   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
   1690     CCValAssign &VA = ArgLocs[i];
   1691     unsigned Arg = Args[VA.getValNo()];
   1692     EVT ArgVT = ArgVTs[VA.getValNo()];
   1693 
   1694     // Promote the value if needed.
   1695     switch (VA.getLocInfo()) {
   1696     default: llvm_unreachable("Unknown loc info!");
   1697     case CCValAssign::Full: break;
   1698     case CCValAssign::SExt: {
   1699       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
   1700              "Unexpected extend");
   1701       bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
   1702                                        Arg, ArgVT, Arg);
   1703       assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
   1704       ArgVT = VA.getLocVT();
   1705       break;
   1706     }
   1707     case CCValAssign::ZExt: {
   1708       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
   1709              "Unexpected extend");
   1710       bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
   1711                                        Arg, ArgVT, Arg);
   1712       assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
   1713       ArgVT = VA.getLocVT();
   1714       break;
   1715     }
   1716     case CCValAssign::AExt: {
   1717       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
   1718              "Unexpected extend");
   1719       bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
   1720                                        Arg, ArgVT, Arg);
   1721       if (!Emitted)
   1722         Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
   1723                                     Arg, ArgVT, Arg);
   1724       if (!Emitted)
   1725         Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
   1726                                     Arg, ArgVT, Arg);
   1727 
   1728       assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
   1729       ArgVT = VA.getLocVT();
   1730       break;
   1731     }
   1732     case CCValAssign::BCvt: {
   1733       unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
   1734                                ISD::BITCAST, Arg, /*TODO: Kill=*/false);
   1735       assert(BC != 0 && "Failed to emit a bitcast!");
   1736       Arg = BC;
   1737       ArgVT = VA.getLocVT();
   1738       break;
   1739     }
   1740     }
   1741 
   1742     if (VA.isRegLoc()) {
   1743       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
   1744               VA.getLocReg()).addReg(Arg);
   1745       RegArgs.push_back(VA.getLocReg());
   1746     } else {
   1747       unsigned LocMemOffset = VA.getLocMemOffset();
   1748       X86AddressMode AM;
   1749       AM.Base.Reg = StackPtr;
   1750       AM.Disp = LocMemOffset;
   1751       const Value *ArgVal = ArgVals[VA.getValNo()];
   1752       ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
   1753 
   1754       if (Flags.isByVal()) {
   1755         X86AddressMode SrcAM;
   1756         SrcAM.Base.Reg = Arg;
   1757         bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
   1758         assert(Res && "memcpy length already checked!"); (void)Res;
   1759       } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
   1760         // If this is a really simple value, emit this with the Value* version
   1761         // of X86FastEmitStore.  If it isn't simple, we don't want to do this,
   1762         // as it can cause us to reevaluate the argument.
   1763         if (!X86FastEmitStore(ArgVT, ArgVal, AM))
   1764           return false;
   1765       } else {
   1766         if (!X86FastEmitStore(ArgVT, Arg, AM))
   1767           return false;
   1768       }
   1769     }
   1770   }
   1771 
   1772   // ELF / PIC requires GOT in the EBX register before function calls via PLT
   1773   // GOT pointer.
   1774   if (Subtarget->isPICStyleGOT()) {
   1775     unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
   1776     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
   1777             X86::EBX).addReg(Base);
   1778   }
   1779 
   1780   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
   1781     // Count the number of XMM registers allocated.
   1782     static const uint16_t XMMArgRegs[] = {
   1783       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
   1784       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
   1785     };
   1786     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
   1787     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
   1788             X86::AL).addImm(NumXMMRegs);
   1789   }
   1790 
   1791   // Issue the call.
   1792   MachineInstrBuilder MIB;
   1793   if (CalleeOp) {
   1794     // Register-indirect call.
   1795     unsigned CallOpc;
   1796     if (Subtarget->is64Bit())
   1797       CallOpc = X86::CALL64r;
   1798     else
   1799       CallOpc = X86::CALL32r;
   1800     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
   1801       .addReg(CalleeOp);
   1802 
   1803   } else {
   1804     // Direct call.
   1805     assert(GV && "Not a direct call");
   1806     unsigned CallOpc;
   1807     if (Subtarget->is64Bit())
   1808       CallOpc = X86::CALL64pcrel32;
   1809     else
   1810       CallOpc = X86::CALLpcrel32;
   1811 
   1812     // See if we need any target-specific flags on the GV operand.
   1813     unsigned char OpFlags = 0;
   1814 
   1815     // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
   1816     // external symbols most go through the PLT in PIC mode.  If the symbol
   1817     // has hidden or protected visibility, or if it is static or local, then
   1818     // we don't need to use the PLT - we can directly call it.
   1819     if (Subtarget->isTargetELF() &&
   1820         TM.getRelocationModel() == Reloc::PIC_ &&
   1821         GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
   1822       OpFlags = X86II::MO_PLT;
   1823     } else if (Subtarget->isPICStyleStubAny() &&
   1824                (GV->isDeclaration() || GV->isWeakForLinker()) &&
   1825                (!Subtarget->getTargetTriple().isMacOSX() ||
   1826                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
   1827       // PC-relative references to external symbols should go through $stub,
   1828       // unless we're building with the leopard linker or later, which
   1829       // automatically synthesizes these stubs.
   1830       OpFlags = X86II::MO_DARWIN_STUB;
   1831     }
   1832 
   1833 
   1834     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
   1835     if (MemIntName)
   1836       MIB.addExternalSymbol(MemIntName, OpFlags);
   1837     else
   1838       MIB.addGlobalAddress(GV, 0, OpFlags);
   1839   }
   1840 
   1841   // Add an implicit use GOT pointer in EBX.
   1842   if (Subtarget->isPICStyleGOT())
   1843     MIB.addReg(X86::EBX);
   1844 
   1845   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
   1846     MIB.addReg(X86::AL);
   1847 
   1848   // Add implicit physical register uses to the call.
   1849   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
   1850     MIB.addReg(RegArgs[i]);
   1851 
   1852   // Add a register mask with the call-preserved registers.
   1853   // Proper defs for return values will be added by setPhysRegsDeadExcept().
   1854   MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
   1855 
   1856   // Issue CALLSEQ_END
   1857   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
   1858   unsigned NumBytesCallee = 0;
   1859   if (!Subtarget->is64Bit() && !Subtarget->isTargetWindows() &&
   1860       CS.paramHasAttr(1, Attribute::StructRet))
   1861     NumBytesCallee = 4;
   1862   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
   1863     .addImm(NumBytes).addImm(NumBytesCallee);
   1864 
   1865   // Build info for return calling conv lowering code.
   1866   // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
   1867   SmallVector<ISD::InputArg, 32> Ins;
   1868   SmallVector<EVT, 4> RetTys;
   1869   ComputeValueVTs(TLI, I->getType(), RetTys);
   1870   for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
   1871     EVT VT = RetTys[i];
   1872     EVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
   1873     unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
   1874     for (unsigned j = 0; j != NumRegs; ++j) {
   1875       ISD::InputArg MyFlags;
   1876       MyFlags.VT = RegisterVT.getSimpleVT();
   1877       MyFlags.Used = !CS.getInstruction()->use_empty();
   1878       if (CS.paramHasAttr(0, Attribute::SExt))
   1879         MyFlags.Flags.setSExt();
   1880       if (CS.paramHasAttr(0, Attribute::ZExt))
   1881         MyFlags.Flags.setZExt();
   1882       if (CS.paramHasAttr(0, Attribute::InReg))
   1883         MyFlags.Flags.setInReg();
   1884       Ins.push_back(MyFlags);
   1885     }
   1886   }
   1887 
   1888   // Now handle call return values.
   1889   SmallVector<unsigned, 4> UsedRegs;
   1890   SmallVector<CCValAssign, 16> RVLocs;
   1891   CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
   1892 		    I->getParent()->getContext());
   1893   unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
   1894   CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
   1895   for (unsigned i = 0; i != RVLocs.size(); ++i) {
   1896     EVT CopyVT = RVLocs[i].getValVT();
   1897     unsigned CopyReg = ResultReg + i;
   1898 
   1899     // If this is a call to a function that returns an fp value on the x87 fp
   1900     // stack, but where we prefer to use the value in xmm registers, copy it
   1901     // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
   1902     if ((RVLocs[i].getLocReg() == X86::ST0 ||
   1903          RVLocs[i].getLocReg() == X86::ST1)) {
   1904       if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
   1905         CopyVT = MVT::f80;
   1906         CopyReg = createResultReg(X86::RFP80RegisterClass);
   1907       }
   1908       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
   1909               CopyReg);
   1910     } else {
   1911       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
   1912               CopyReg).addReg(RVLocs[i].getLocReg());
   1913       UsedRegs.push_back(RVLocs[i].getLocReg());
   1914     }
   1915 
   1916     if (CopyVT != RVLocs[i].getValVT()) {
   1917       // Round the F80 the right size, which also moves to the appropriate xmm
   1918       // register. This is accomplished by storing the F80 value in memory and
   1919       // then loading it back. Ewww...
   1920       EVT ResVT = RVLocs[i].getValVT();
   1921       unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
   1922       unsigned MemSize = ResVT.getSizeInBits()/8;
   1923       int FI = MFI.CreateStackObject(MemSize, MemSize, false);
   1924       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
   1925                                 TII.get(Opc)), FI)
   1926         .addReg(CopyReg);
   1927       Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
   1928       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
   1929                                 TII.get(Opc), ResultReg + i), FI);
   1930     }
   1931   }
   1932 
   1933   if (RVLocs.size())
   1934     UpdateValueMap(I, ResultReg, RVLocs.size());
   1935 
   1936   // Set all unused physreg defs as dead.
   1937   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
   1938 
   1939   return true;
   1940 }
   1941 
   1942 
   1943 bool
   1944 X86FastISel::TargetSelectInstruction(const Instruction *I)  {
   1945   switch (I->getOpcode()) {
   1946   default: break;
   1947   case Instruction::Load:
   1948     return X86SelectLoad(I);
   1949   case Instruction::Store:
   1950     return X86SelectStore(I);
   1951   case Instruction::Ret:
   1952     return X86SelectRet(I);
   1953   case Instruction::ICmp:
   1954   case Instruction::FCmp:
   1955     return X86SelectCmp(I);
   1956   case Instruction::ZExt:
   1957     return X86SelectZExt(I);
   1958   case Instruction::Br:
   1959     return X86SelectBranch(I);
   1960   case Instruction::Call:
   1961     return X86SelectCall(I);
   1962   case Instruction::LShr:
   1963   case Instruction::AShr:
   1964   case Instruction::Shl:
   1965     return X86SelectShift(I);
   1966   case Instruction::Select:
   1967     return X86SelectSelect(I);
   1968   case Instruction::Trunc:
   1969     return X86SelectTrunc(I);
   1970   case Instruction::FPExt:
   1971     return X86SelectFPExt(I);
   1972   case Instruction::FPTrunc:
   1973     return X86SelectFPTrunc(I);
   1974   case Instruction::IntToPtr: // Deliberate fall-through.
   1975   case Instruction::PtrToInt: {
   1976     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
   1977     EVT DstVT = TLI.getValueType(I->getType());
   1978     if (DstVT.bitsGT(SrcVT))
   1979       return X86SelectZExt(I);
   1980     if (DstVT.bitsLT(SrcVT))
   1981       return X86SelectTrunc(I);
   1982     unsigned Reg = getRegForValue(I->getOperand(0));
   1983     if (Reg == 0) return false;
   1984     UpdateValueMap(I, Reg);
   1985     return true;
   1986   }
   1987   }
   1988 
   1989   return false;
   1990 }
   1991 
   1992 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
   1993   MVT VT;
   1994   if (!isTypeLegal(C->getType(), VT))
   1995     return false;
   1996 
   1997   // Get opcode and regclass of the output for the given load instruction.
   1998   unsigned Opc = 0;
   1999   const TargetRegisterClass *RC = NULL;
   2000   switch (VT.SimpleTy) {
   2001   default: return false;
   2002   case MVT::i8:
   2003     Opc = X86::MOV8rm;
   2004     RC  = X86::GR8RegisterClass;
   2005     break;
   2006   case MVT::i16:
   2007     Opc = X86::MOV16rm;
   2008     RC  = X86::GR16RegisterClass;
   2009     break;
   2010   case MVT::i32:
   2011     Opc = X86::MOV32rm;
   2012     RC  = X86::GR32RegisterClass;
   2013     break;
   2014   case MVT::i64:
   2015     // Must be in x86-64 mode.
   2016     Opc = X86::MOV64rm;
   2017     RC  = X86::GR64RegisterClass;
   2018     break;
   2019   case MVT::f32:
   2020     if (X86ScalarSSEf32) {
   2021       Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
   2022       RC  = X86::FR32RegisterClass;
   2023     } else {
   2024       Opc = X86::LD_Fp32m;
   2025       RC  = X86::RFP32RegisterClass;
   2026     }
   2027     break;
   2028   case MVT::f64:
   2029     if (X86ScalarSSEf64) {
   2030       Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
   2031       RC  = X86::FR64RegisterClass;
   2032     } else {
   2033       Opc = X86::LD_Fp64m;
   2034       RC  = X86::RFP64RegisterClass;
   2035     }
   2036     break;
   2037   case MVT::f80:
   2038     // No f80 support yet.
   2039     return false;
   2040   }
   2041 
   2042   // Materialize addresses with LEA instructions.
   2043   if (isa<GlobalValue>(C)) {
   2044     X86AddressMode AM;
   2045     if (X86SelectAddress(C, AM)) {
   2046       // If the expression is just a basereg, then we're done, otherwise we need
   2047       // to emit an LEA.
   2048       if (AM.BaseType == X86AddressMode::RegBase &&
   2049           AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
   2050         return AM.Base.Reg;
   2051 
   2052       Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
   2053       unsigned ResultReg = createResultReg(RC);
   2054       addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
   2055                              TII.get(Opc), ResultReg), AM);
   2056       return ResultReg;
   2057     }
   2058     return 0;
   2059   }
   2060 
   2061   // MachineConstantPool wants an explicit alignment.
   2062   unsigned Align = TD.getPrefTypeAlignment(C->getType());
   2063   if (Align == 0) {
   2064     // Alignment of vector types.  FIXME!
   2065     Align = TD.getTypeAllocSize(C->getType());
   2066   }
   2067 
   2068   // x86-32 PIC requires a PIC base register for constant pools.
   2069   unsigned PICBase = 0;
   2070   unsigned char OpFlag = 0;
   2071   if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
   2072     OpFlag = X86II::MO_PIC_BASE_OFFSET;
   2073     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
   2074   } else if (Subtarget->isPICStyleGOT()) {
   2075     OpFlag = X86II::MO_GOTOFF;
   2076     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
   2077   } else if (Subtarget->isPICStyleRIPRel() &&
   2078              TM.getCodeModel() == CodeModel::Small) {
   2079     PICBase = X86::RIP;
   2080   }
   2081 
   2082   // Create the load from the constant pool.
   2083   unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
   2084   unsigned ResultReg = createResultReg(RC);
   2085   addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
   2086                                    TII.get(Opc), ResultReg),
   2087                            MCPOffset, PICBase, OpFlag);
   2088 
   2089   return ResultReg;
   2090 }
   2091 
   2092 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
   2093   // Fail on dynamic allocas. At this point, getRegForValue has already
   2094   // checked its CSE maps, so if we're here trying to handle a dynamic
   2095   // alloca, we're not going to succeed. X86SelectAddress has a
   2096   // check for dynamic allocas, because it's called directly from
   2097   // various places, but TargetMaterializeAlloca also needs a check
   2098   // in order to avoid recursion between getRegForValue,
   2099   // X86SelectAddrss, and TargetMaterializeAlloca.
   2100   if (!FuncInfo.StaticAllocaMap.count(C))
   2101     return 0;
   2102 
   2103   X86AddressMode AM;
   2104   if (!X86SelectAddress(C, AM))
   2105     return 0;
   2106   unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
   2107   const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
   2108   unsigned ResultReg = createResultReg(RC);
   2109   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
   2110                          TII.get(Opc), ResultReg), AM);
   2111   return ResultReg;
   2112 }
   2113 
   2114 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
   2115   MVT VT;
   2116   if (!isTypeLegal(CF->getType(), VT))
   2117     return false;
   2118 
   2119   // Get opcode and regclass for the given zero.
   2120   unsigned Opc = 0;
   2121   const TargetRegisterClass *RC = NULL;
   2122   switch (VT.SimpleTy) {
   2123     default: return false;
   2124     case MVT::f32:
   2125       if (X86ScalarSSEf32) {
   2126         Opc = X86::FsFLD0SS;
   2127         RC  = X86::FR32RegisterClass;
   2128       } else {
   2129         Opc = X86::LD_Fp032;
   2130         RC  = X86::RFP32RegisterClass;
   2131       }
   2132       break;
   2133     case MVT::f64:
   2134       if (X86ScalarSSEf64) {
   2135         Opc = X86::FsFLD0SD;
   2136         RC  = X86::FR64RegisterClass;
   2137       } else {
   2138         Opc = X86::LD_Fp064;
   2139         RC  = X86::RFP64RegisterClass;
   2140       }
   2141       break;
   2142     case MVT::f80:
   2143       // No f80 support yet.
   2144       return false;
   2145   }
   2146 
   2147   unsigned ResultReg = createResultReg(RC);
   2148   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
   2149   return ResultReg;
   2150 }
   2151 
   2152 
   2153 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
   2154 /// vreg is being provided by the specified load instruction.  If possible,
   2155 /// try to fold the load as an operand to the instruction, returning true if
   2156 /// possible.
   2157 bool X86FastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
   2158                                 const LoadInst *LI) {
   2159   X86AddressMode AM;
   2160   if (!X86SelectAddress(LI->getOperand(0), AM))
   2161     return false;
   2162 
   2163   X86InstrInfo &XII = (X86InstrInfo&)TII;
   2164 
   2165   unsigned Size = TD.getTypeAllocSize(LI->getType());
   2166   unsigned Alignment = LI->getAlignment();
   2167 
   2168   SmallVector<MachineOperand, 8> AddrOps;
   2169   AM.getFullAddress(AddrOps);
   2170 
   2171   MachineInstr *Result =
   2172     XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
   2173   if (Result == 0) return false;
   2174 
   2175   FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
   2176   MI->eraseFromParent();
   2177   return true;
   2178 }
   2179 
   2180 
   2181 namespace llvm {
   2182   FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo) {
   2183     return new X86FastISel(funcInfo);
   2184   }
   2185 }
   2186