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