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