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