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