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