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