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