3a05c8a885227f32c78cb5fa8dda7c9623586f37
[oota-llvm.git] / lib / Target / X86 / X86FastISel.cpp
1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the X86-specific support for the FastISel class. Much
11 // of the target-specific code is generated by tablegen in the file
12 // X86GenFastISel.inc, which is #included here.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32
33 using namespace llvm;
34
35 class X86FastISel : public FastISel {
36   /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
37   /// make the right decision when generating code for different targets.
38   const X86Subtarget *Subtarget;
39
40   /// StackPtr - Register used as the stack pointer.
41   ///
42   unsigned StackPtr;
43
44   /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87 
45   /// floating point ops.
46   /// When SSE is available, use it for f32 operations.
47   /// When SSE2 is available, use it for f64 operations.
48   bool X86ScalarSSEf64;
49   bool X86ScalarSSEf32;
50
51 public:
52   explicit X86FastISel(MachineFunction &mf,
53                        MachineModuleInfo *mmi,
54                        DwarfWriter *dw,
55                        DenseMap<const Value *, unsigned> &vm,
56                        DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
57                        DenseMap<const AllocaInst *, int> &am
58 #ifndef NDEBUG
59                        , SmallSet<Instruction*, 8> &cil
60 #endif
61                        )
62     : FastISel(mf, mmi, dw, vm, bm, am
63 #ifndef NDEBUG
64                , cil
65 #endif
66                ) {
67     Subtarget = &TM.getSubtarget<X86Subtarget>();
68     StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
69     X86ScalarSSEf64 = Subtarget->hasSSE2();
70     X86ScalarSSEf32 = Subtarget->hasSSE1();
71   }
72
73   virtual bool TargetSelectInstruction(Instruction *I);
74
75 #include "X86GenFastISel.inc"
76
77 private:
78   bool X86FastEmitCompare(Value *LHS, Value *RHS, MVT VT);
79   
80   bool X86FastEmitLoad(MVT VT, const X86AddressMode &AM, unsigned &RR);
81
82   bool X86FastEmitStore(MVT VT, Value *Val,
83                         const X86AddressMode &AM);
84   bool X86FastEmitStore(MVT VT, unsigned Val,
85                         const X86AddressMode &AM);
86
87   bool X86FastEmitExtend(ISD::NodeType Opc, MVT DstVT, unsigned Src, MVT SrcVT,
88                          unsigned &ResultReg);
89   
90   bool X86SelectAddress(Value *V, X86AddressMode &AM, bool isCall);
91
92   bool X86SelectLoad(Instruction *I);
93   
94   bool X86SelectStore(Instruction *I);
95
96   bool X86SelectCmp(Instruction *I);
97
98   bool X86SelectZExt(Instruction *I);
99
100   bool X86SelectBranch(Instruction *I);
101
102   bool X86SelectShift(Instruction *I);
103
104   bool X86SelectSelect(Instruction *I);
105
106   bool X86SelectTrunc(Instruction *I);
107  
108   bool X86SelectFPExt(Instruction *I);
109   bool X86SelectFPTrunc(Instruction *I);
110
111   bool X86SelectExtractValue(Instruction *I);
112
113   bool X86VisitIntrinsicCall(CallInst &I, unsigned Intrinsic);
114   bool X86SelectCall(Instruction *I);
115
116   CCAssignFn *CCAssignFnForCall(unsigned CC, bool isTailCall = false);
117
118   const X86InstrInfo *getInstrInfo() const {
119     return getTargetMachine()->getInstrInfo();
120   }
121   const X86TargetMachine *getTargetMachine() const {
122     return static_cast<const X86TargetMachine *>(&TM);
123   }
124
125   unsigned TargetMaterializeConstant(Constant *C);
126
127   unsigned TargetMaterializeAlloca(AllocaInst *C);
128
129   /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
130   /// computed in an SSE register, not on the X87 floating point stack.
131   bool isScalarFPTypeInSSEReg(MVT VT) const {
132     return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
133       (VT == MVT::f32 && X86ScalarSSEf32);   // f32 is when SSE1
134   }
135
136   bool isTypeLegal(const Type *Ty, MVT &VT, bool AllowI1 = false);
137 };
138
139 bool X86FastISel::isTypeLegal(const Type *Ty, MVT &VT, bool AllowI1) {
140   VT = TLI.getValueType(Ty, /*HandleUnknown=*/true);
141   if (VT == MVT::Other || !VT.isSimple())
142     // Unhandled type. Halt "fast" selection and bail.
143     return false;
144   
145   // For now, require SSE/SSE2 for performing floating-point operations,
146   // since x87 requires additional work.
147   if (VT == MVT::f64 && !X86ScalarSSEf64)
148      return false;
149   if (VT == MVT::f32 && !X86ScalarSSEf32)
150      return false;
151   // Similarly, no f80 support yet.
152   if (VT == MVT::f80)
153     return false;
154   // We only handle legal types. For example, on x86-32 the instruction
155   // selector contains all of the 64-bit instructions from x86-64,
156   // under the assumption that i64 won't be used if the target doesn't
157   // support it.
158   return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
159 }
160
161 #include "X86GenCallingConv.inc"
162
163 /// CCAssignFnForCall - Selects the correct CCAssignFn for a given calling
164 /// convention.
165 CCAssignFn *X86FastISel::CCAssignFnForCall(unsigned CC, bool isTaillCall) {
166   if (Subtarget->is64Bit()) {
167     if (Subtarget->isTargetWin64())
168       return CC_X86_Win64_C;
169     else if (CC == CallingConv::Fast && isTaillCall)
170       return CC_X86_64_TailCall;
171     else
172       return CC_X86_64_C;
173   }
174
175   if (CC == CallingConv::X86_FastCall)
176     return CC_X86_32_FastCall;
177   else if (CC == CallingConv::Fast)
178     return CC_X86_32_FastCC;
179   else
180     return CC_X86_32_C;
181 }
182
183 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
184 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
185 /// Return true and the result register by reference if it is possible.
186 bool X86FastISel::X86FastEmitLoad(MVT VT, const X86AddressMode &AM,
187                                   unsigned &ResultReg) {
188   // Get opcode and regclass of the output for the given load instruction.
189   unsigned Opc = 0;
190   const TargetRegisterClass *RC = NULL;
191   switch (VT.getSimpleVT()) {
192   default: return false;
193   case MVT::i8:
194     Opc = X86::MOV8rm;
195     RC  = X86::GR8RegisterClass;
196     break;
197   case MVT::i16:
198     Opc = X86::MOV16rm;
199     RC  = X86::GR16RegisterClass;
200     break;
201   case MVT::i32:
202     Opc = X86::MOV32rm;
203     RC  = X86::GR32RegisterClass;
204     break;
205   case MVT::i64:
206     // Must be in x86-64 mode.
207     Opc = X86::MOV64rm;
208     RC  = X86::GR64RegisterClass;
209     break;
210   case MVT::f32:
211     if (Subtarget->hasSSE1()) {
212       Opc = X86::MOVSSrm;
213       RC  = X86::FR32RegisterClass;
214     } else {
215       Opc = X86::LD_Fp32m;
216       RC  = X86::RFP32RegisterClass;
217     }
218     break;
219   case MVT::f64:
220     if (Subtarget->hasSSE2()) {
221       Opc = X86::MOVSDrm;
222       RC  = X86::FR64RegisterClass;
223     } else {
224       Opc = X86::LD_Fp64m;
225       RC  = X86::RFP64RegisterClass;
226     }
227     break;
228   case MVT::f80:
229     // No f80 support yet.
230     return false;
231   }
232
233   ResultReg = createResultReg(RC);
234   addFullAddress(BuildMI(MBB, 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(MVT 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()) {
248   case MVT::f80: // No f80 support yet.
249   default: return false;
250   case MVT::i8:  Opc = X86::MOV8mr;  break;
251   case MVT::i16: Opc = X86::MOV16mr; break;
252   case MVT::i32: Opc = X86::MOV32mr; break;
253   case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
254   case MVT::f32:
255     Opc = Subtarget->hasSSE1() ? X86::MOVSSmr : X86::ST_Fp32m;
256     break;
257   case MVT::f64:
258     Opc = Subtarget->hasSSE2() ? X86::MOVSDmr : X86::ST_Fp64m;
259     break;
260   }
261   
262   addFullAddress(BuildMI(MBB, TII.get(Opc)), AM).addReg(Val);
263   return true;
264 }
265
266 bool X86FastISel::X86FastEmitStore(MVT VT, Value *Val,
267                                    const X86AddressMode &AM) {
268   // Handle 'null' like i32/i64 0.
269   if (isa<ConstantPointerNull>(Val))
270     Val = Constant::getNullValue(TD.getIntPtrType());
271   
272   // If this is a store of a simple constant, fold the constant into the store.
273   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
274     unsigned Opc = 0;
275     switch (VT.getSimpleVT()) {
276     default: break;
277     case MVT::i8:  Opc = X86::MOV8mi;  break;
278     case MVT::i16: Opc = X86::MOV16mi; break;
279     case MVT::i32: Opc = X86::MOV32mi; break;
280     case MVT::i64:
281       // Must be a 32-bit sign extended value.
282       if ((int)CI->getSExtValue() == CI->getSExtValue())
283         Opc = X86::MOV64mi32;
284       break;
285     }
286     
287     if (Opc) {
288       addFullAddress(BuildMI(MBB, TII.get(Opc)), AM).addImm(CI->getSExtValue());
289       return true;
290     }
291   }
292   
293   unsigned ValReg = getRegForValue(Val);
294   if (ValReg == 0)
295     return false;    
296  
297   return X86FastEmitStore(VT, ValReg, AM);
298 }
299
300 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
301 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
302 /// ISD::SIGN_EXTEND).
303 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, MVT DstVT,
304                                     unsigned Src, MVT SrcVT,
305                                     unsigned &ResultReg) {
306   unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src);
307   
308   if (RR != 0) {
309     ResultReg = RR;
310     return true;
311   } else
312     return false;
313 }
314
315 /// X86SelectAddress - Attempt to fill in an address from the given value.
316 ///
317 bool X86FastISel::X86SelectAddress(Value *V, X86AddressMode &AM, bool isCall) {
318   User *U;
319   unsigned Opcode = Instruction::UserOp1;
320   if (Instruction *I = dyn_cast<Instruction>(V)) {
321     Opcode = I->getOpcode();
322     U = I;
323   } else if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
324     Opcode = C->getOpcode();
325     U = C;
326   }
327
328   switch (Opcode) {
329   default: break;
330   case Instruction::BitCast:
331     // Look past bitcasts.
332     return X86SelectAddress(U->getOperand(0), AM, isCall);
333
334   case Instruction::IntToPtr:
335     // Look past no-op inttoptrs.
336     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
337       return X86SelectAddress(U->getOperand(0), AM, isCall);
338     break;
339
340   case Instruction::PtrToInt:
341     // Look past no-op ptrtoints.
342     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
343       return X86SelectAddress(U->getOperand(0), AM, isCall);
344     break;
345
346   case Instruction::Alloca: {
347     if (isCall) break;
348     // Do static allocas.
349     const AllocaInst *A = cast<AllocaInst>(V);
350     DenseMap<const AllocaInst*, int>::iterator SI = StaticAllocaMap.find(A);
351     if (SI != StaticAllocaMap.end()) {
352       AM.BaseType = X86AddressMode::FrameIndexBase;
353       AM.Base.FrameIndex = SI->second;
354       return true;
355     }
356     break;
357   }
358
359   case Instruction::Add: {
360     if (isCall) break;
361     // Adds of constants are common and easy enough.
362     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
363       uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
364       // They have to fit in the 32-bit signed displacement field though.
365       if (isInt32(Disp)) {
366         AM.Disp = (uint32_t)Disp;
367         return X86SelectAddress(U->getOperand(0), AM, isCall);
368       }
369     }
370     break;
371   }
372
373   case Instruction::GetElementPtr: {
374     if (isCall) break;
375     // Pattern-match simple GEPs.
376     uint64_t Disp = (int32_t)AM.Disp;
377     unsigned IndexReg = AM.IndexReg;
378     unsigned Scale = AM.Scale;
379     gep_type_iterator GTI = gep_type_begin(U);
380     // Iterate through the indices, folding what we can. Constants can be
381     // folded, and one dynamic index can be handled, if the scale is supported.
382     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end();
383          i != e; ++i, ++GTI) {
384       Value *Op = *i;
385       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
386         const StructLayout *SL = TD.getStructLayout(STy);
387         unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
388         Disp += SL->getElementOffset(Idx);
389       } else {
390         uint64_t S = TD.getTypePaddedSize(GTI.getIndexedType());
391         if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
392           // Constant-offset addressing.
393           Disp += CI->getSExtValue() * S;
394         } else if (IndexReg == 0 &&
395                    (!AM.GV ||
396                     !getTargetMachine()->symbolicAddressesAreRIPRel()) &&
397                    (S == 1 || S == 2 || S == 4 || S == 8)) {
398           // Scaled-index addressing.
399           Scale = S;
400           IndexReg = getRegForGEPIndex(Op);
401           if (IndexReg == 0)
402             return false;
403         } else
404           // Unsupported.
405           goto unsupported_gep;
406       }
407     }
408     // Check for displacement overflow.
409     if (!isInt32(Disp))
410       break;
411     // Ok, the GEP indices were covered by constant-offset and scaled-index
412     // addressing. Update the address state and move on to examining the base.
413     AM.IndexReg = IndexReg;
414     AM.Scale = Scale;
415     AM.Disp = (uint32_t)Disp;
416     return X86SelectAddress(U->getOperand(0), AM, isCall);
417   unsupported_gep:
418     // Ok, the GEP indices weren't all covered.
419     break;
420   }
421   }
422
423   // Handle constant address.
424   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
425     // Can't handle alternate code models yet.
426     if (TM.getCodeModel() != CodeModel::Default &&
427         TM.getCodeModel() != CodeModel::Small)
428       return false;
429
430     // RIP-relative addresses can't have additional register operands.
431     if (getTargetMachine()->symbolicAddressesAreRIPRel() &&
432         (AM.Base.Reg != 0 || AM.IndexReg != 0))
433       return false;
434
435     // Set up the basic address.
436     AM.GV = GV;
437     if (!isCall &&
438         TM.getRelocationModel() == Reloc::PIC_ &&
439         !Subtarget->is64Bit())
440       AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(&MF);
441
442     // Emit an extra load if the ABI requires it.
443     if (Subtarget->GVRequiresExtraLoad(GV, TM, isCall)) {
444       // Check to see if we've already materialized this
445       // value in a register in this block.
446       if (unsigned Reg = LocalValueMap[V]) {
447         AM.Base.Reg = Reg;
448         AM.GV = 0;
449         return true;
450       }
451       // Issue load from stub if necessary.
452       unsigned Opc = 0;
453       const TargetRegisterClass *RC = NULL;
454       if (TLI.getPointerTy() == MVT::i32) {
455         Opc = X86::MOV32rm;
456         RC  = X86::GR32RegisterClass;
457       } else {
458         Opc = X86::MOV64rm;
459         RC  = X86::GR64RegisterClass;
460       }
461
462       X86AddressMode StubAM;
463       StubAM.Base.Reg = AM.Base.Reg;
464       StubAM.GV = AM.GV;
465       unsigned ResultReg = createResultReg(RC);
466       addFullAddress(BuildMI(MBB, TII.get(Opc), ResultReg), StubAM);
467
468       // Now construct the final address. Note that the Disp, Scale,
469       // and Index values may already be set here.
470       AM.Base.Reg = ResultReg;
471       AM.GV = 0;
472
473       // Prevent loading GV stub multiple times in same MBB.
474       LocalValueMap[V] = AM.Base.Reg;
475     }
476     return true;
477   }
478
479   // If all else fails, try to materialize the value in a register.
480   if (!AM.GV || !getTargetMachine()->symbolicAddressesAreRIPRel()) {
481     if (AM.Base.Reg == 0) {
482       AM.Base.Reg = getRegForValue(V);
483       return AM.Base.Reg != 0;
484     }
485     if (AM.IndexReg == 0) {
486       assert(AM.Scale == 1 && "Scale with no index!");
487       AM.IndexReg = getRegForValue(V);
488       return AM.IndexReg != 0;
489     }
490   }
491
492   return false;
493 }
494
495 /// X86SelectStore - Select and emit code to implement store instructions.
496 bool X86FastISel::X86SelectStore(Instruction* I) {
497   MVT VT;
498   if (!isTypeLegal(I->getOperand(0)->getType(), VT))
499     return false;
500
501   X86AddressMode AM;
502   if (!X86SelectAddress(I->getOperand(1), AM, false))
503     return false;
504
505   return X86FastEmitStore(VT, I->getOperand(0), AM);
506 }
507
508 /// X86SelectLoad - Select and emit code to implement load instructions.
509 ///
510 bool X86FastISel::X86SelectLoad(Instruction *I)  {
511   MVT VT;
512   if (!isTypeLegal(I->getType(), VT))
513     return false;
514
515   X86AddressMode AM;
516   if (!X86SelectAddress(I->getOperand(0), AM, false))
517     return false;
518
519   unsigned ResultReg = 0;
520   if (X86FastEmitLoad(VT, AM, ResultReg)) {
521     UpdateValueMap(I, ResultReg);
522     return true;
523   }
524   return false;
525 }
526
527 static unsigned X86ChooseCmpOpcode(MVT VT) {
528   switch (VT.getSimpleVT()) {
529   default:       return 0;
530   case MVT::i8:  return X86::CMP8rr;
531   case MVT::i16: return X86::CMP16rr;
532   case MVT::i32: return X86::CMP32rr;
533   case MVT::i64: return X86::CMP64rr;
534   case MVT::f32: return X86::UCOMISSrr;
535   case MVT::f64: return X86::UCOMISDrr;
536   }
537 }
538
539 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
540 /// of the comparison, return an opcode that works for the compare (e.g.
541 /// CMP32ri) otherwise return 0.
542 static unsigned X86ChooseCmpImmediateOpcode(MVT VT, ConstantInt *RHSC) {
543   switch (VT.getSimpleVT()) {
544   // Otherwise, we can't fold the immediate into this comparison.
545   default: return 0;
546   case MVT::i8: return X86::CMP8ri;
547   case MVT::i16: return X86::CMP16ri;
548   case MVT::i32: return X86::CMP32ri;
549   case MVT::i64:
550     // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
551     // field.
552     if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
553       return X86::CMP64ri32;
554     return 0;
555   }
556 }
557
558 bool X86FastISel::X86FastEmitCompare(Value *Op0, Value *Op1, MVT VT) {
559   unsigned Op0Reg = getRegForValue(Op0);
560   if (Op0Reg == 0) return false;
561   
562   // Handle 'null' like i32/i64 0.
563   if (isa<ConstantPointerNull>(Op1))
564     Op1 = Constant::getNullValue(TD.getIntPtrType());
565   
566   // We have two options: compare with register or immediate.  If the RHS of
567   // the compare is an immediate that we can fold into this compare, use
568   // CMPri, otherwise use CMPrr.
569   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
570     if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
571       BuildMI(MBB, TII.get(CompareImmOpc)).addReg(Op0Reg)
572                                           .addImm(Op1C->getSExtValue());
573       return true;
574     }
575   }
576   
577   unsigned CompareOpc = X86ChooseCmpOpcode(VT);
578   if (CompareOpc == 0) return false;
579     
580   unsigned Op1Reg = getRegForValue(Op1);
581   if (Op1Reg == 0) return false;
582   BuildMI(MBB, TII.get(CompareOpc)).addReg(Op0Reg).addReg(Op1Reg);
583   
584   return true;
585 }
586
587 bool X86FastISel::X86SelectCmp(Instruction *I) {
588   CmpInst *CI = cast<CmpInst>(I);
589
590   MVT VT;
591   if (!isTypeLegal(I->getOperand(0)->getType(), VT))
592     return false;
593
594   unsigned ResultReg = createResultReg(&X86::GR8RegClass);
595   unsigned SetCCOpc;
596   bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
597   switch (CI->getPredicate()) {
598   case CmpInst::FCMP_OEQ: {
599     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
600       return false;
601     
602     unsigned EReg = createResultReg(&X86::GR8RegClass);
603     unsigned NPReg = createResultReg(&X86::GR8RegClass);
604     BuildMI(MBB, TII.get(X86::SETEr), EReg);
605     BuildMI(MBB, TII.get(X86::SETNPr), NPReg);
606     BuildMI(MBB, TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
607     UpdateValueMap(I, ResultReg);
608     return true;
609   }
610   case CmpInst::FCMP_UNE: {
611     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
612       return false;
613
614     unsigned NEReg = createResultReg(&X86::GR8RegClass);
615     unsigned PReg = createResultReg(&X86::GR8RegClass);
616     BuildMI(MBB, TII.get(X86::SETNEr), NEReg);
617     BuildMI(MBB, TII.get(X86::SETPr), PReg);
618     BuildMI(MBB, TII.get(X86::OR8rr), ResultReg).addReg(PReg).addReg(NEReg);
619     UpdateValueMap(I, ResultReg);
620     return true;
621   }
622   case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
623   case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
624   case CmpInst::FCMP_OLT: SwapArgs = true;  SetCCOpc = X86::SETAr;  break;
625   case CmpInst::FCMP_OLE: SwapArgs = true;  SetCCOpc = X86::SETAEr; break;
626   case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
627   case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
628   case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr;  break;
629   case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr;  break;
630   case CmpInst::FCMP_UGT: SwapArgs = true;  SetCCOpc = X86::SETBr;  break;
631   case CmpInst::FCMP_UGE: SwapArgs = true;  SetCCOpc = X86::SETBEr; break;
632   case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
633   case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
634   
635   case CmpInst::ICMP_EQ:  SwapArgs = false; SetCCOpc = X86::SETEr;  break;
636   case CmpInst::ICMP_NE:  SwapArgs = false; SetCCOpc = X86::SETNEr; break;
637   case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr;  break;
638   case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
639   case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr;  break;
640   case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
641   case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr;  break;
642   case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
643   case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr;  break;
644   case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
645   default:
646     return false;
647   }
648
649   Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
650   if (SwapArgs)
651     std::swap(Op0, Op1);
652
653   // Emit a compare of Op0/Op1.
654   if (!X86FastEmitCompare(Op0, Op1, VT))
655     return false;
656   
657   BuildMI(MBB, TII.get(SetCCOpc), ResultReg);
658   UpdateValueMap(I, ResultReg);
659   return true;
660 }
661
662 bool X86FastISel::X86SelectZExt(Instruction *I) {
663   // Special-case hack: The only i1 values we know how to produce currently
664   // set the upper bits of an i8 value to zero.
665   if (I->getType() == Type::Int8Ty &&
666       I->getOperand(0)->getType() == Type::Int1Ty) {
667     unsigned ResultReg = getRegForValue(I->getOperand(0));
668     if (ResultReg == 0) return false;
669     UpdateValueMap(I, ResultReg);
670     return true;
671   }
672
673   return false;
674 }
675
676
677 bool X86FastISel::X86SelectBranch(Instruction *I) {
678   // Unconditional branches are selected by tablegen-generated code.
679   // Handle a conditional branch.
680   BranchInst *BI = cast<BranchInst>(I);
681   MachineBasicBlock *TrueMBB = MBBMap[BI->getSuccessor(0)];
682   MachineBasicBlock *FalseMBB = MBBMap[BI->getSuccessor(1)];
683
684   // Fold the common case of a conditional branch with a comparison.
685   if (CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
686     if (CI->hasOneUse()) {
687       MVT VT = TLI.getValueType(CI->getOperand(0)->getType());
688
689       // Try to take advantage of fallthrough opportunities.
690       CmpInst::Predicate Predicate = CI->getPredicate();
691       if (MBB->isLayoutSuccessor(TrueMBB)) {
692         std::swap(TrueMBB, FalseMBB);
693         Predicate = CmpInst::getInversePredicate(Predicate);
694       }
695
696       bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
697       unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
698
699       switch (Predicate) {
700       case CmpInst::FCMP_OEQ:
701         std::swap(TrueMBB, FalseMBB);
702         Predicate = CmpInst::FCMP_UNE;
703         // FALL THROUGH
704       case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE; break;
705       case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA;  break;
706       case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE; break;
707       case CmpInst::FCMP_OLT: SwapArgs = true;  BranchOpc = X86::JA;  break;
708       case CmpInst::FCMP_OLE: SwapArgs = true;  BranchOpc = X86::JAE; break;
709       case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE; break;
710       case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP; break;
711       case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP;  break;
712       case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE;  break;
713       case CmpInst::FCMP_UGT: SwapArgs = true;  BranchOpc = X86::JB;  break;
714       case CmpInst::FCMP_UGE: SwapArgs = true;  BranchOpc = X86::JBE; break;
715       case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB;  break;
716       case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE; break;
717           
718       case CmpInst::ICMP_EQ:  SwapArgs = false; BranchOpc = X86::JE;  break;
719       case CmpInst::ICMP_NE:  SwapArgs = false; BranchOpc = X86::JNE; break;
720       case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA;  break;
721       case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE; break;
722       case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB;  break;
723       case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE; break;
724       case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG;  break;
725       case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE; break;
726       case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL;  break;
727       case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE; break;
728       default:
729         return false;
730       }
731       
732       Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
733       if (SwapArgs)
734         std::swap(Op0, Op1);
735
736       // Emit a compare of the LHS and RHS, setting the flags.
737       if (!X86FastEmitCompare(Op0, Op1, VT))
738         return false;
739       
740       BuildMI(MBB, TII.get(BranchOpc)).addMBB(TrueMBB);
741
742       if (Predicate == CmpInst::FCMP_UNE) {
743         // X86 requires a second branch to handle UNE (and OEQ,
744         // which is mapped to UNE above).
745         BuildMI(MBB, TII.get(X86::JP)).addMBB(TrueMBB);
746       }
747
748       FastEmitBranch(FalseMBB);
749       MBB->addSuccessor(TrueMBB);
750       return true;
751     }
752   } else if (ExtractValueInst *EI =
753              dyn_cast<ExtractValueInst>(BI->getCondition())) {
754     // Check to see if the branch instruction is from an "arithmetic with
755     // overflow" intrinsic. The main way these intrinsics are used is:
756     //
757     //   %t = call { i32, i1 } @llvm.sadd.with.overflow.i32(i32 %v1, i32 %v2)
758     //   %sum = extractvalue { i32, i1 } %t, 0
759     //   %obit = extractvalue { i32, i1 } %t, 1
760     //   br i1 %obit, label %overflow, label %normal
761     //
762     // The %sum and %obit are converted in an ADD and a SETO/SETB before
763     // reaching the branch. Therefore, we search backwards through the MBB
764     // looking for the SETO/SETB instruction. If an instruction modifies the
765     // EFLAGS register before we reach the SETO/SETB instruction, then we can't
766     // convert the branch into a JO/JB instruction.
767
768     Value *Agg = EI->getAggregateOperand();
769
770     if (CallInst *CI = dyn_cast<CallInst>(Agg)) {
771       Function *F = CI->getCalledFunction();
772
773       if (F && F->isDeclaration()) {
774         switch (F->getIntrinsicID()) {
775         default: break;
776         case Intrinsic::sadd_with_overflow:
777         case Intrinsic::uadd_with_overflow: {
778           const MachineInstr *SetMI = 0;
779           unsigned Reg = lookUpRegForValue(EI);
780
781           for (MachineBasicBlock::const_reverse_iterator
782                  RI = MBB->rbegin(), RE = MBB->rend(); RI != RE; ++RI) {
783             const MachineInstr &MI = *RI;
784
785             if (MI.modifiesRegister(Reg)) {
786               unsigned Src, Dst;
787
788               if (getInstrInfo()->isMoveInstr(MI, Src, Dst)) {
789                 Reg = Src;
790                 continue;
791               }
792
793               SetMI = &MI;
794               break;
795             }
796
797             const TargetInstrDesc &TID = MI.getDesc();
798             const unsigned *ImpDefs = TID.getImplicitDefs();
799
800             if (TID.hasUnmodeledSideEffects()) break;
801
802             bool ModifiesEFlags = false;
803
804             if (ImpDefs) {
805               for (unsigned u = 0; ImpDefs[u]; ++u)
806                 if (ImpDefs[u] == X86::EFLAGS) {
807                   ModifiesEFlags = true;
808                   break;
809                 }
810             }
811
812             if (ModifiesEFlags) break;
813           }
814
815           if (SetMI) {
816             unsigned OpCode = SetMI->getOpcode();
817
818             if (OpCode == X86::SETOr || OpCode == X86::SETBr) {
819               BuildMI(MBB, TII.get((OpCode == X86::SETOr) ? 
820                                    X86::JO : X86::JB)).addMBB(TrueMBB);
821               FastEmitBranch(FalseMBB);
822               MBB->addSuccessor(TrueMBB);
823               return true;
824             }
825           }
826         }
827         }
828       }
829     }
830   }
831
832   // Otherwise do a clumsy setcc and re-test it.
833   unsigned OpReg = getRegForValue(BI->getCondition());
834   if (OpReg == 0) return false;
835
836   BuildMI(MBB, TII.get(X86::TEST8rr)).addReg(OpReg).addReg(OpReg);
837   BuildMI(MBB, TII.get(X86::JNE)).addMBB(TrueMBB);
838   FastEmitBranch(FalseMBB);
839   MBB->addSuccessor(TrueMBB);
840   return true;
841 }
842
843 bool X86FastISel::X86SelectShift(Instruction *I) {
844   unsigned CReg = 0, OpReg = 0, OpImm = 0;
845   const TargetRegisterClass *RC = NULL;
846   if (I->getType() == Type::Int8Ty) {
847     CReg = X86::CL;
848     RC = &X86::GR8RegClass;
849     switch (I->getOpcode()) {
850     case Instruction::LShr: OpReg = X86::SHR8rCL; OpImm = X86::SHR8ri; break;
851     case Instruction::AShr: OpReg = X86::SAR8rCL; OpImm = X86::SAR8ri; break;
852     case Instruction::Shl:  OpReg = X86::SHL8rCL; OpImm = X86::SHL8ri; break;
853     default: return false;
854     }
855   } else if (I->getType() == Type::Int16Ty) {
856     CReg = X86::CX;
857     RC = &X86::GR16RegClass;
858     switch (I->getOpcode()) {
859     case Instruction::LShr: OpReg = X86::SHR16rCL; OpImm = X86::SHR16ri; break;
860     case Instruction::AShr: OpReg = X86::SAR16rCL; OpImm = X86::SAR16ri; break;
861     case Instruction::Shl:  OpReg = X86::SHL16rCL; OpImm = X86::SHL16ri; break;
862     default: return false;
863     }
864   } else if (I->getType() == Type::Int32Ty) {
865     CReg = X86::ECX;
866     RC = &X86::GR32RegClass;
867     switch (I->getOpcode()) {
868     case Instruction::LShr: OpReg = X86::SHR32rCL; OpImm = X86::SHR32ri; break;
869     case Instruction::AShr: OpReg = X86::SAR32rCL; OpImm = X86::SAR32ri; break;
870     case Instruction::Shl:  OpReg = X86::SHL32rCL; OpImm = X86::SHL32ri; break;
871     default: return false;
872     }
873   } else if (I->getType() == Type::Int64Ty) {
874     CReg = X86::RCX;
875     RC = &X86::GR64RegClass;
876     switch (I->getOpcode()) {
877     case Instruction::LShr: OpReg = X86::SHR64rCL; OpImm = X86::SHR64ri; break;
878     case Instruction::AShr: OpReg = X86::SAR64rCL; OpImm = X86::SAR64ri; break;
879     case Instruction::Shl:  OpReg = X86::SHL64rCL; OpImm = X86::SHL64ri; break;
880     default: return false;
881     }
882   } else {
883     return false;
884   }
885
886   MVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
887   if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
888     return false;
889
890   unsigned Op0Reg = getRegForValue(I->getOperand(0));
891   if (Op0Reg == 0) return false;
892   
893   // Fold immediate in shl(x,3).
894   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
895     unsigned ResultReg = createResultReg(RC);
896     BuildMI(MBB, TII.get(OpImm), 
897             ResultReg).addReg(Op0Reg).addImm(CI->getZExtValue() & 0xff);
898     UpdateValueMap(I, ResultReg);
899     return true;
900   }
901   
902   unsigned Op1Reg = getRegForValue(I->getOperand(1));
903   if (Op1Reg == 0) return false;
904   TII.copyRegToReg(*MBB, MBB->end(), CReg, Op1Reg, RC, RC);
905
906   // The shift instruction uses X86::CL. If we defined a super-register
907   // of X86::CL, emit an EXTRACT_SUBREG to precisely describe what
908   // we're doing here.
909   if (CReg != X86::CL)
910     BuildMI(MBB, TII.get(TargetInstrInfo::EXTRACT_SUBREG), X86::CL)
911       .addReg(CReg).addImm(X86::SUBREG_8BIT);
912
913   unsigned ResultReg = createResultReg(RC);
914   BuildMI(MBB, TII.get(OpReg), ResultReg).addReg(Op0Reg);
915   UpdateValueMap(I, ResultReg);
916   return true;
917 }
918
919 bool X86FastISel::X86SelectSelect(Instruction *I) {
920   MVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
921   if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
922     return false;
923   
924   unsigned Opc = 0;
925   const TargetRegisterClass *RC = NULL;
926   if (VT.getSimpleVT() == MVT::i16) {
927     Opc = X86::CMOVE16rr;
928     RC = &X86::GR16RegClass;
929   } else if (VT.getSimpleVT() == MVT::i32) {
930     Opc = X86::CMOVE32rr;
931     RC = &X86::GR32RegClass;
932   } else if (VT.getSimpleVT() == MVT::i64) {
933     Opc = X86::CMOVE64rr;
934     RC = &X86::GR64RegClass;
935   } else {
936     return false; 
937   }
938
939   unsigned Op0Reg = getRegForValue(I->getOperand(0));
940   if (Op0Reg == 0) return false;
941   unsigned Op1Reg = getRegForValue(I->getOperand(1));
942   if (Op1Reg == 0) return false;
943   unsigned Op2Reg = getRegForValue(I->getOperand(2));
944   if (Op2Reg == 0) return false;
945
946   BuildMI(MBB, TII.get(X86::TEST8rr)).addReg(Op0Reg).addReg(Op0Reg);
947   unsigned ResultReg = createResultReg(RC);
948   BuildMI(MBB, TII.get(Opc), ResultReg).addReg(Op1Reg).addReg(Op2Reg);
949   UpdateValueMap(I, ResultReg);
950   return true;
951 }
952
953 bool X86FastISel::X86SelectFPExt(Instruction *I) {
954   // fpext from float to double.
955   if (Subtarget->hasSSE2() && I->getType() == Type::DoubleTy) {
956     Value *V = I->getOperand(0);
957     if (V->getType() == Type::FloatTy) {
958       unsigned OpReg = getRegForValue(V);
959       if (OpReg == 0) return false;
960       unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
961       BuildMI(MBB, TII.get(X86::CVTSS2SDrr), ResultReg).addReg(OpReg);
962       UpdateValueMap(I, ResultReg);
963       return true;
964     }
965   }
966
967   return false;
968 }
969
970 bool X86FastISel::X86SelectFPTrunc(Instruction *I) {
971   if (Subtarget->hasSSE2()) {
972     if (I->getType() == Type::FloatTy) {
973       Value *V = I->getOperand(0);
974       if (V->getType() == Type::DoubleTy) {
975         unsigned OpReg = getRegForValue(V);
976         if (OpReg == 0) return false;
977         unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
978         BuildMI(MBB, TII.get(X86::CVTSD2SSrr), ResultReg).addReg(OpReg);
979         UpdateValueMap(I, ResultReg);
980         return true;
981       }
982     }
983   }
984
985   return false;
986 }
987
988 bool X86FastISel::X86SelectTrunc(Instruction *I) {
989   if (Subtarget->is64Bit())
990     // All other cases should be handled by the tblgen generated code.
991     return false;
992   MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
993   MVT DstVT = TLI.getValueType(I->getType());
994   if (DstVT != MVT::i8)
995     // All other cases should be handled by the tblgen generated code.
996     return false;
997   if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
998     // All other cases should be handled by the tblgen generated code.
999     return false;
1000
1001   unsigned InputReg = getRegForValue(I->getOperand(0));
1002   if (!InputReg)
1003     // Unhandled operand.  Halt "fast" selection and bail.
1004     return false;
1005
1006   // First issue a copy to GR16_ or GR32_.
1007   unsigned CopyOpc = (SrcVT == MVT::i16) ? X86::MOV16to16_ : X86::MOV32to32_;
1008   const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1009     ? X86::GR16_RegisterClass : X86::GR32_RegisterClass;
1010   unsigned CopyReg = createResultReg(CopyRC);
1011   BuildMI(MBB, TII.get(CopyOpc), CopyReg).addReg(InputReg);
1012
1013   // Then issue an extract_subreg.
1014   unsigned ResultReg = FastEmitInst_extractsubreg(CopyReg, X86::SUBREG_8BIT);
1015   if (!ResultReg)
1016     return false;
1017
1018   UpdateValueMap(I, ResultReg);
1019   return true;
1020 }
1021
1022 bool X86FastISel::X86SelectExtractValue(Instruction *I) {
1023   ExtractValueInst *EI = cast<ExtractValueInst>(I);
1024   Value *Agg = EI->getAggregateOperand();
1025
1026   if (CallInst *CI = dyn_cast<CallInst>(Agg)) {
1027     Function *F = CI->getCalledFunction();
1028
1029     if (F && F->isDeclaration()) {
1030       switch (F->getIntrinsicID()) {
1031       default: break;
1032       case Intrinsic::sadd_with_overflow:
1033       case Intrinsic::uadd_with_overflow:
1034         // Cheat a little. We know that the registers for "add" and "seto" are
1035         // allocated sequentially. However, we only keep track of the register
1036         // for "add" in the value map. Use extractvalue's index to get the
1037         // correct register for "seto".
1038         UpdateValueMap(I, lookUpRegForValue(Agg) + *EI->idx_begin());
1039         return true;
1040       }
1041     }
1042   }
1043
1044   return false;
1045 }
1046
1047 bool X86FastISel::X86VisitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1048   // FIXME: Handle more intrinsics.
1049   switch (Intrinsic) {
1050   default: return false;
1051   case Intrinsic::sadd_with_overflow:
1052   case Intrinsic::uadd_with_overflow: {
1053     // Replace "add with overflow" intrinsics with an "add" instruction followed
1054     // by a seto/setc instruction. Later on, when the "extractvalue"
1055     // instructions are encountered, we use the fact that two registers were
1056     // created sequentially to get the correct registers for the "sum" and the
1057     // "overflow bit".
1058     MVT VT;
1059     const Function *Callee = I.getCalledFunction();
1060     const Type *RetTy =
1061       cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1062
1063     if (!isTypeLegal(RetTy, VT))
1064       return false;
1065
1066     Value *Op1 = I.getOperand(1);
1067     Value *Op2 = I.getOperand(2);
1068     unsigned Reg1 = getRegForValue(Op1);
1069     unsigned Reg2 = getRegForValue(Op2);
1070
1071     if (Reg1 == 0 || Reg2 == 0)
1072       // FIXME: Handle values *not* in registers.
1073       return false;
1074
1075     unsigned OpC = 0;
1076
1077     if (VT == MVT::i32)
1078       OpC = X86::ADD32rr;
1079     else if (VT == MVT::i64)
1080       OpC = X86::ADD64rr;
1081     else
1082       return false;
1083
1084     unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1085     BuildMI(MBB, TII.get(OpC), ResultReg).addReg(Reg1).addReg(Reg2);
1086     UpdateValueMap(&I, ResultReg);
1087
1088     ResultReg = createResultReg(TLI.getRegClassFor(MVT::i8));
1089     BuildMI(MBB, TII.get((Intrinsic == Intrinsic::sadd_with_overflow) ?
1090                          X86::SETOr : X86::SETBr), ResultReg);
1091     return true;
1092   }
1093   }
1094 }
1095
1096 bool X86FastISel::X86SelectCall(Instruction *I) {
1097   CallInst *CI = cast<CallInst>(I);
1098   Value *Callee = I->getOperand(0);
1099
1100   // Can't handle inline asm yet.
1101   if (isa<InlineAsm>(Callee))
1102     return false;
1103
1104   // Handle intrinsic calls.
1105   if (Function *F = CI->getCalledFunction())
1106     if (F->isDeclaration())
1107       if (unsigned IID = F->getIntrinsicID())
1108         return X86VisitIntrinsicCall(*CI, IID);
1109
1110   // Handle only C and fastcc calling conventions for now.
1111   CallSite CS(CI);
1112   unsigned CC = CS.getCallingConv();
1113   if (CC != CallingConv::C &&
1114       CC != CallingConv::Fast &&
1115       CC != CallingConv::X86_FastCall)
1116     return false;
1117
1118   // Let SDISel handle vararg functions.
1119   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1120   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1121   if (FTy->isVarArg())
1122     return false;
1123
1124   // Handle *simple* calls for now.
1125   const Type *RetTy = CS.getType();
1126   MVT RetVT;
1127   if (RetTy == Type::VoidTy)
1128     RetVT = MVT::isVoid;
1129   else if (!isTypeLegal(RetTy, RetVT, true))
1130     return false;
1131
1132   // Materialize callee address in a register. FIXME: GV address can be
1133   // handled with a CALLpcrel32 instead.
1134   X86AddressMode CalleeAM;
1135   if (!X86SelectAddress(Callee, CalleeAM, true))
1136     return false;
1137   unsigned CalleeOp = 0;
1138   GlobalValue *GV = 0;
1139   if (CalleeAM.Base.Reg != 0) {
1140     assert(CalleeAM.GV == 0);
1141     CalleeOp = CalleeAM.Base.Reg;
1142   } else if (CalleeAM.GV != 0) {
1143     assert(CalleeAM.GV != 0);
1144     GV = CalleeAM.GV;
1145   } else
1146     return false;
1147
1148   // Allow calls which produce i1 results.
1149   bool AndToI1 = false;
1150   if (RetVT == MVT::i1) {
1151     RetVT = MVT::i8;
1152     AndToI1 = true;
1153   }
1154
1155   // Deal with call operands first.
1156   SmallVector<Value*, 8> ArgVals;
1157   SmallVector<unsigned, 8> Args;
1158   SmallVector<MVT, 8> ArgVTs;
1159   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1160   Args.reserve(CS.arg_size());
1161   ArgVals.reserve(CS.arg_size());
1162   ArgVTs.reserve(CS.arg_size());
1163   ArgFlags.reserve(CS.arg_size());
1164   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1165        i != e; ++i) {
1166     unsigned Arg = getRegForValue(*i);
1167     if (Arg == 0)
1168       return false;
1169     ISD::ArgFlagsTy Flags;
1170     unsigned AttrInd = i - CS.arg_begin() + 1;
1171     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1172       Flags.setSExt();
1173     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1174       Flags.setZExt();
1175
1176     // FIXME: Only handle *easy* calls for now.
1177     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1178         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1179         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1180         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1181       return false;
1182
1183     const Type *ArgTy = (*i)->getType();
1184     MVT ArgVT;
1185     if (!isTypeLegal(ArgTy, ArgVT))
1186       return false;
1187     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1188     Flags.setOrigAlign(OriginalAlignment);
1189
1190     Args.push_back(Arg);
1191     ArgVals.push_back(*i);
1192     ArgVTs.push_back(ArgVT);
1193     ArgFlags.push_back(Flags);
1194   }
1195
1196   // Analyze operands of the call, assigning locations to each operand.
1197   SmallVector<CCValAssign, 16> ArgLocs;
1198   CCState CCInfo(CC, false, TM, ArgLocs);
1199   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
1200
1201   // Get a count of how many bytes are to be pushed on the stack.
1202   unsigned NumBytes = CCInfo.getNextStackOffset();
1203
1204   // Issue CALLSEQ_START
1205   unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1206   BuildMI(MBB, TII.get(AdjStackDown)).addImm(NumBytes);
1207
1208   // Process argument: walk the register/memloc assignments, inserting
1209   // copies / loads.
1210   SmallVector<unsigned, 4> RegArgs;
1211   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1212     CCValAssign &VA = ArgLocs[i];
1213     unsigned Arg = Args[VA.getValNo()];
1214     MVT ArgVT = ArgVTs[VA.getValNo()];
1215   
1216     // Promote the value if needed.
1217     switch (VA.getLocInfo()) {
1218     default: assert(0 && "Unknown loc info!");
1219     case CCValAssign::Full: break;
1220     case CCValAssign::SExt: {
1221       bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1222                                        Arg, ArgVT, Arg);
1223       assert(Emitted && "Failed to emit a sext!"); Emitted=Emitted;
1224       Emitted = true;
1225       ArgVT = VA.getLocVT();
1226       break;
1227     }
1228     case CCValAssign::ZExt: {
1229       bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1230                                        Arg, ArgVT, Arg);
1231       assert(Emitted && "Failed to emit a zext!"); Emitted=Emitted;
1232       Emitted = true;
1233       ArgVT = VA.getLocVT();
1234       break;
1235     }
1236     case CCValAssign::AExt: {
1237       bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1238                                        Arg, ArgVT, Arg);
1239       if (!Emitted)
1240         Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1241                                     Arg, ArgVT, Arg);
1242       if (!Emitted)
1243         Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1244                                     Arg, ArgVT, Arg);
1245       
1246       assert(Emitted && "Failed to emit a aext!"); Emitted=Emitted;
1247       ArgVT = VA.getLocVT();
1248       break;
1249     }
1250     }
1251     
1252     if (VA.isRegLoc()) {
1253       TargetRegisterClass* RC = TLI.getRegClassFor(ArgVT);
1254       bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), VA.getLocReg(),
1255                                       Arg, RC, RC);
1256       assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1257       Emitted = true;
1258       RegArgs.push_back(VA.getLocReg());
1259     } else {
1260       unsigned LocMemOffset = VA.getLocMemOffset();
1261       X86AddressMode AM;
1262       AM.Base.Reg = StackPtr;
1263       AM.Disp = LocMemOffset;
1264       Value *ArgVal = ArgVals[VA.getValNo()];
1265       
1266       // If this is a really simple value, emit this with the Value* version of
1267       // X86FastEmitStore.  If it isn't simple, we don't want to do this, as it
1268       // can cause us to reevaluate the argument.
1269       if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal))
1270         X86FastEmitStore(ArgVT, ArgVal, AM);
1271       else
1272         X86FastEmitStore(ArgVT, Arg, AM);
1273     }
1274   }
1275
1276   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1277   // GOT pointer.  
1278   if (!Subtarget->is64Bit() &&
1279       TM.getRelocationModel() == Reloc::PIC_ &&
1280       Subtarget->isPICStyleGOT()) {
1281     TargetRegisterClass *RC = X86::GR32RegisterClass;
1282     unsigned Base = getInstrInfo()->getGlobalBaseReg(&MF);
1283     bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), X86::EBX, Base, RC, RC);
1284     assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1285     Emitted = true;
1286   }
1287
1288   // Issue the call.
1289   unsigned CallOpc = CalleeOp
1290     ? (Subtarget->is64Bit() ? X86::CALL64r       : X86::CALL32r)
1291     : (Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32);
1292   MachineInstrBuilder MIB = CalleeOp
1293     ? BuildMI(MBB, TII.get(CallOpc)).addReg(CalleeOp)
1294     : BuildMI(MBB, TII.get(CallOpc)).addGlobalAddress(GV);
1295
1296   // Add an implicit use GOT pointer in EBX.
1297   if (!Subtarget->is64Bit() &&
1298       TM.getRelocationModel() == Reloc::PIC_ &&
1299       Subtarget->isPICStyleGOT())
1300     MIB.addReg(X86::EBX);
1301
1302   // Add implicit physical register uses to the call.
1303   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1304     MIB.addReg(RegArgs[i]);
1305
1306   // Issue CALLSEQ_END
1307   unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1308   BuildMI(MBB, TII.get(AdjStackUp)).addImm(NumBytes).addImm(0);
1309
1310   // Now handle call return value (if any).
1311   if (RetVT.getSimpleVT() != MVT::isVoid) {
1312     SmallVector<CCValAssign, 16> RVLocs;
1313     CCState CCInfo(CC, false, TM, RVLocs);
1314     CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
1315
1316     // Copy all of the result registers out of their specified physreg.
1317     assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
1318     MVT CopyVT = RVLocs[0].getValVT();
1319     TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1320     TargetRegisterClass *SrcRC = DstRC;
1321     
1322     // If this is a call to a function that returns an fp value on the x87 fp
1323     // stack, but where we prefer to use the value in xmm registers, copy it
1324     // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1325     if ((RVLocs[0].getLocReg() == X86::ST0 ||
1326          RVLocs[0].getLocReg() == X86::ST1) &&
1327         isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
1328       CopyVT = MVT::f80;
1329       SrcRC = X86::RSTRegisterClass;
1330       DstRC = X86::RFP80RegisterClass;
1331     }
1332
1333     unsigned ResultReg = createResultReg(DstRC);
1334     bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1335                                     RVLocs[0].getLocReg(), DstRC, SrcRC);
1336     assert(Emitted && "Failed to emit a copy instruction!"); Emitted=Emitted;
1337     Emitted = true;
1338     if (CopyVT != RVLocs[0].getValVT()) {
1339       // Round the F80 the right size, which also moves to the appropriate xmm
1340       // register. This is accomplished by storing the F80 value in memory and
1341       // then loading it back. Ewww...
1342       MVT ResVT = RVLocs[0].getValVT();
1343       unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1344       unsigned MemSize = ResVT.getSizeInBits()/8;
1345       int FI = MFI.CreateStackObject(MemSize, MemSize);
1346       addFrameReference(BuildMI(MBB, TII.get(Opc)), FI).addReg(ResultReg);
1347       DstRC = ResVT == MVT::f32
1348         ? X86::FR32RegisterClass : X86::FR64RegisterClass;
1349       Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1350       ResultReg = createResultReg(DstRC);
1351       addFrameReference(BuildMI(MBB, TII.get(Opc), ResultReg), FI);
1352     }
1353
1354     if (AndToI1) {
1355       // Mask out all but lowest bit for some call which produces an i1.
1356       unsigned AndResult = createResultReg(X86::GR8RegisterClass);
1357       BuildMI(MBB, TII.get(X86::AND8ri), AndResult).addReg(ResultReg).addImm(1);
1358       ResultReg = AndResult;
1359     }
1360
1361     UpdateValueMap(I, ResultReg);
1362   }
1363
1364   return true;
1365 }
1366
1367
1368 bool
1369 X86FastISel::TargetSelectInstruction(Instruction *I)  {
1370   switch (I->getOpcode()) {
1371   default: break;
1372   case Instruction::Load:
1373     return X86SelectLoad(I);
1374   case Instruction::Store:
1375     return X86SelectStore(I);
1376   case Instruction::ICmp:
1377   case Instruction::FCmp:
1378     return X86SelectCmp(I);
1379   case Instruction::ZExt:
1380     return X86SelectZExt(I);
1381   case Instruction::Br:
1382     return X86SelectBranch(I);
1383   case Instruction::Call:
1384     return X86SelectCall(I);
1385   case Instruction::LShr:
1386   case Instruction::AShr:
1387   case Instruction::Shl:
1388     return X86SelectShift(I);
1389   case Instruction::Select:
1390     return X86SelectSelect(I);
1391   case Instruction::Trunc:
1392     return X86SelectTrunc(I);
1393   case Instruction::FPExt:
1394     return X86SelectFPExt(I);
1395   case Instruction::FPTrunc:
1396     return X86SelectFPTrunc(I);
1397   case Instruction::ExtractValue:
1398     return X86SelectExtractValue(I);
1399   }
1400
1401   return false;
1402 }
1403
1404 unsigned X86FastISel::TargetMaterializeConstant(Constant *C) {
1405   MVT VT;
1406   if (!isTypeLegal(C->getType(), VT))
1407     return false;
1408   
1409   // Get opcode and regclass of the output for the given load instruction.
1410   unsigned Opc = 0;
1411   const TargetRegisterClass *RC = NULL;
1412   switch (VT.getSimpleVT()) {
1413   default: return false;
1414   case MVT::i8:
1415     Opc = X86::MOV8rm;
1416     RC  = X86::GR8RegisterClass;
1417     break;
1418   case MVT::i16:
1419     Opc = X86::MOV16rm;
1420     RC  = X86::GR16RegisterClass;
1421     break;
1422   case MVT::i32:
1423     Opc = X86::MOV32rm;
1424     RC  = X86::GR32RegisterClass;
1425     break;
1426   case MVT::i64:
1427     // Must be in x86-64 mode.
1428     Opc = X86::MOV64rm;
1429     RC  = X86::GR64RegisterClass;
1430     break;
1431   case MVT::f32:
1432     if (Subtarget->hasSSE1()) {
1433       Opc = X86::MOVSSrm;
1434       RC  = X86::FR32RegisterClass;
1435     } else {
1436       Opc = X86::LD_Fp32m;
1437       RC  = X86::RFP32RegisterClass;
1438     }
1439     break;
1440   case MVT::f64:
1441     if (Subtarget->hasSSE2()) {
1442       Opc = X86::MOVSDrm;
1443       RC  = X86::FR64RegisterClass;
1444     } else {
1445       Opc = X86::LD_Fp64m;
1446       RC  = X86::RFP64RegisterClass;
1447     }
1448     break;
1449   case MVT::f80:
1450     // No f80 support yet.
1451     return false;
1452   }
1453   
1454   // Materialize addresses with LEA instructions.
1455   if (isa<GlobalValue>(C)) {
1456     X86AddressMode AM;
1457     if (X86SelectAddress(C, AM, false)) {
1458       if (TLI.getPointerTy() == MVT::i32)
1459         Opc = X86::LEA32r;
1460       else
1461         Opc = X86::LEA64r;
1462       unsigned ResultReg = createResultReg(RC);
1463       addFullAddress(BuildMI(MBB, TII.get(Opc), ResultReg), AM);
1464       return ResultReg;
1465     }
1466     return 0;
1467   }
1468   
1469   // MachineConstantPool wants an explicit alignment.
1470   unsigned Align = TD.getPreferredTypeAlignmentShift(C->getType());
1471   if (Align == 0) {
1472     // Alignment of vector types.  FIXME!
1473     Align = TD.getTypePaddedSize(C->getType());
1474     Align = Log2_64(Align);
1475   }
1476   
1477   // x86-32 PIC requires a PIC base register for constant pools.
1478   unsigned PICBase = 0;
1479   if (TM.getRelocationModel() == Reloc::PIC_ &&
1480       !Subtarget->is64Bit())
1481     PICBase = getInstrInfo()->getGlobalBaseReg(&MF);
1482
1483   // Create the load from the constant pool.
1484   unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
1485   unsigned ResultReg = createResultReg(RC);
1486   addConstantPoolReference(BuildMI(MBB, TII.get(Opc), ResultReg), MCPOffset,
1487                            PICBase);
1488
1489   return ResultReg;
1490 }
1491
1492 unsigned X86FastISel::TargetMaterializeAlloca(AllocaInst *C) {
1493   // Fail on dynamic allocas. At this point, getRegForValue has already
1494   // checked its CSE maps, so if we're here trying to handle a dynamic
1495   // alloca, we're not going to succeed. X86SelectAddress has a
1496   // check for dynamic allocas, because it's called directly from
1497   // various places, but TargetMaterializeAlloca also needs a check
1498   // in order to avoid recursion between getRegForValue,
1499   // X86SelectAddrss, and TargetMaterializeAlloca.
1500   if (!StaticAllocaMap.count(C))
1501     return 0;
1502
1503   X86AddressMode AM;
1504   if (!X86SelectAddress(C, AM, false))
1505     return 0;
1506   unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
1507   TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
1508   unsigned ResultReg = createResultReg(RC);
1509   addFullAddress(BuildMI(MBB, TII.get(Opc), ResultReg), AM);
1510   return ResultReg;
1511 }
1512
1513 namespace llvm {
1514   llvm::FastISel *X86::createFastISel(MachineFunction &mf,
1515                         MachineModuleInfo *mmi,
1516                         DwarfWriter *dw,
1517                         DenseMap<const Value *, unsigned> &vm,
1518                         DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
1519                         DenseMap<const AllocaInst *, int> &am
1520 #ifndef NDEBUG
1521                         , SmallSet<Instruction*, 8> &cil
1522 #endif
1523                         ) {
1524     return new X86FastISel(mf, mmi, dw, vm, bm, am
1525 #ifndef NDEBUG
1526                            , cil
1527 #endif
1528                            );
1529   }
1530 }