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