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