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