4584bde7adc86a763f590532bd45dad92293c371
[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
31 using namespace llvm;
32
33 class X86FastISel : public FastISel {
34   /// MFI - Keep track of objects allocated on the stack.
35   ///
36   MachineFrameInfo *MFI;
37
38   /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
39   /// make the right decision when generating code for different targets.
40   const X86Subtarget *Subtarget;
41
42   /// StackPtr - Register used as the stack pointer.
43   ///
44   unsigned StackPtr;
45
46   /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87 
47   /// floating point ops.
48   /// When SSE is available, use it for f32 operations.
49   /// When SSE2 is available, use it for f64 operations.
50   bool X86ScalarSSEf64;
51   bool X86ScalarSSEf32;
52
53 public:
54   explicit X86FastISel(MachineFunction &mf,
55                        DenseMap<const Value *, unsigned> &vm,
56                        DenseMap<const BasicBlock *, MachineBasicBlock *> &bm)
57     : FastISel(mf, vm, bm), MFI(MF.getFrameInfo()) {
58     Subtarget = &TM.getSubtarget<X86Subtarget>();
59     StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
60     X86ScalarSSEf64 = Subtarget->hasSSE2();
61     X86ScalarSSEf32 = Subtarget->hasSSE1();
62   }
63
64   virtual bool TargetSelectInstruction(Instruction *I);
65
66 #include "X86GenFastISel.inc"
67
68 private:
69   bool X86FastEmitLoad(MVT VT, unsigned Op0, Value *V, unsigned &RR);
70
71   bool X86FastEmitStore(MVT VT, unsigned Val,
72                         unsigned Ptr, unsigned Offset, Value *V);
73
74   bool X86FastEmitExtend(ISD::NodeType Opc, MVT DstVT, unsigned Src, MVT SrcVT,
75                          unsigned &ResultReg);
76   
77   bool X86SelectConstAddr(Value *V, unsigned &Op0, bool isCall = false);
78
79   bool X86SelectLoad(Instruction *I);
80   
81   bool X86SelectStore(Instruction *I);
82
83   bool X86SelectCmp(Instruction *I);
84
85   bool X86SelectZExt(Instruction *I);
86
87   bool X86SelectBranch(Instruction *I);
88
89   bool X86SelectShift(Instruction *I);
90
91   bool X86SelectSelect(Instruction *I);
92
93   bool X86SelectTrunc(Instruction *I);
94
95   bool X86SelectCall(Instruction *I);
96
97   CCAssignFn *CCAssignFnForCall(unsigned CC, bool isTailCall = false);
98
99   unsigned TargetMaterializeConstant(Constant *C, MachineConstantPool* MCP);
100
101   /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
102   /// computed in an SSE register, not on the X87 floating point stack.
103   bool isScalarFPTypeInSSEReg(MVT VT) const {
104     return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
105       (VT == MVT::f32 && X86ScalarSSEf32);   // f32 is when SSE1
106   }
107
108 };
109
110 static bool isTypeLegal(const Type *Ty, const TargetLowering &TLI, MVT &VT,
111                         bool AllowI1 = false) {
112   VT = MVT::getMVT(Ty, /*HandleUnknown=*/true);
113   if (VT == MVT::Other || !VT.isSimple())
114     // Unhandled type. Halt "fast" selection and bail.
115     return false;
116   if (VT == MVT::iPTR)
117     // Use pointer type.
118     VT = TLI.getPointerTy();
119   // We only handle legal types. For example, on x86-32 the instruction
120   // selector contains all of the 64-bit instructions from x86-64,
121   // under the assumption that i64 won't be used if the target doesn't
122   // support it.
123   return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
124 }
125
126 #include "X86GenCallingConv.inc"
127
128 /// CCAssignFnForCall - Selects the correct CCAssignFn for a given calling
129 /// convention.
130 CCAssignFn *X86FastISel::CCAssignFnForCall(unsigned CC, bool isTaillCall) {
131   if (Subtarget->is64Bit()) {
132     if (Subtarget->isTargetWin64())
133       return CC_X86_Win64_C;
134     else if (CC == CallingConv::Fast && isTaillCall)
135       return CC_X86_64_TailCall;
136     else
137       return CC_X86_64_C;
138   }
139
140   if (CC == CallingConv::X86_FastCall)
141     return CC_X86_32_FastCall;
142   else if (CC == CallingConv::Fast && isTaillCall)
143     return CC_X86_32_TailCall;
144   else if (CC == CallingConv::Fast)
145     return CC_X86_32_FastCC;
146   else
147     return CC_X86_32_C;
148 }
149
150 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
151 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
152 /// Return true and the result register by reference if it is possible.
153 bool X86FastISel::X86FastEmitLoad(MVT VT, unsigned Ptr, Value *GV,
154                                   unsigned &ResultReg) {
155   // Get opcode and regclass of the output for the given load instruction.
156   unsigned Opc = 0;
157   const TargetRegisterClass *RC = NULL;
158   switch (VT.getSimpleVT()) {
159   default: return false;
160   case MVT::i8:
161     Opc = X86::MOV8rm;
162     RC  = X86::GR8RegisterClass;
163     break;
164   case MVT::i16:
165     Opc = X86::MOV16rm;
166     RC  = X86::GR16RegisterClass;
167     break;
168   case MVT::i32:
169     Opc = X86::MOV32rm;
170     RC  = X86::GR32RegisterClass;
171     break;
172   case MVT::i64:
173     // Must be in x86-64 mode.
174     Opc = X86::MOV64rm;
175     RC  = X86::GR64RegisterClass;
176     break;
177   case MVT::f32:
178     if (Subtarget->hasSSE1()) {
179       Opc = X86::MOVSSrm;
180       RC  = X86::FR32RegisterClass;
181     } else {
182       Opc = X86::LD_Fp32m;
183       RC  = X86::RFP32RegisterClass;
184     }
185     break;
186   case MVT::f64:
187     if (Subtarget->hasSSE2()) {
188       Opc = X86::MOVSDrm;
189       RC  = X86::FR64RegisterClass;
190     } else {
191       Opc = X86::LD_Fp64m;
192       RC  = X86::RFP64RegisterClass;
193     }
194     break;
195   case MVT::f80:
196     Opc = X86::LD_Fp80m;
197     RC  = X86::RFP80RegisterClass;
198     break;
199   }
200
201   ResultReg = createResultReg(RC);
202   X86AddressMode AM;
203   if (Ptr)
204     // Address is in register.
205     AM.Base.Reg = Ptr;
206   else
207     AM.GV = cast<GlobalValue>(GV);
208   addFullAddress(BuildMI(MBB, TII.get(Opc), ResultReg), AM);
209   return true;
210 }
211
212 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
213 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
214 /// and a displacement offset, or a GlobalAddress,
215 /// i.e. V. Return true if it is possible.
216 bool
217 X86FastISel::X86FastEmitStore(MVT VT, unsigned Val,
218                               unsigned Ptr, unsigned Offset, Value *V) {
219   // Get opcode and regclass of the output for the given store instruction.
220   unsigned Opc = 0;
221   const TargetRegisterClass *RC = NULL;
222   switch (VT.getSimpleVT()) {
223   default: return false;
224   case MVT::i8:
225     Opc = X86::MOV8mr;
226     RC  = X86::GR8RegisterClass;
227     break;
228   case MVT::i16:
229     Opc = X86::MOV16mr;
230     RC  = X86::GR16RegisterClass;
231     break;
232   case MVT::i32:
233     Opc = X86::MOV32mr;
234     RC  = X86::GR32RegisterClass;
235     break;
236   case MVT::i64:
237     // Must be in x86-64 mode.
238     Opc = X86::MOV64mr;
239     RC  = X86::GR64RegisterClass;
240     break;
241   case MVT::f32:
242     if (Subtarget->hasSSE1()) {
243       Opc = X86::MOVSSmr;
244       RC  = X86::FR32RegisterClass;
245     } else {
246       Opc = X86::ST_Fp32m;
247       RC  = X86::RFP32RegisterClass;
248     }
249     break;
250   case MVT::f64:
251     if (Subtarget->hasSSE2()) {
252       Opc = X86::MOVSDmr;
253       RC  = X86::FR64RegisterClass;
254     } else {
255       Opc = X86::ST_Fp64m;
256       RC  = X86::RFP64RegisterClass;
257     }
258     break;
259   case MVT::f80:
260     Opc = X86::ST_FP80m;
261     RC  = X86::RFP80RegisterClass;
262     break;
263   }
264
265   X86AddressMode AM;
266   if (Ptr) {
267     // Address is in register.
268     AM.Base.Reg = Ptr;
269     AM.Disp = Offset;
270   } else
271     AM.GV = cast<GlobalValue>(V);
272   addFullAddress(BuildMI(MBB, TII.get(Opc)), AM).addReg(Val);
273   return true;
274 }
275
276 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
277 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
278 /// ISD::SIGN_EXTEND).
279 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, MVT DstVT,
280                                     unsigned Src, MVT SrcVT,
281                                     unsigned &ResultReg) {
282   ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src);
283   return ResultReg != 0;
284 }
285
286 /// X86SelectConstAddr - Select and emit code to materialize constant address.
287 /// 
288 bool X86FastISel::X86SelectConstAddr(Value *V, unsigned &Op0, bool isCall) {
289   // FIXME: Only GlobalAddress for now.
290   GlobalValue *GV = dyn_cast<GlobalValue>(V);
291   if (!GV)
292     return false;
293
294   if (Subtarget->GVRequiresExtraLoad(GV, TM, isCall)) {
295     // Issue load from stub if necessary.
296     unsigned Opc = 0;
297     const TargetRegisterClass *RC = NULL;
298     if (TLI.getPointerTy() == MVT::i32) {
299       Opc = X86::MOV32rm;
300       RC  = X86::GR32RegisterClass;
301     } else {
302       Opc = X86::MOV64rm;
303       RC  = X86::GR64RegisterClass;
304     }
305     Op0 = createResultReg(RC);
306     X86AddressMode AM;
307     AM.GV = GV;
308     addFullAddress(BuildMI(MBB, TII.get(Opc), Op0), AM);
309     // Prevent loading GV stub multiple times in same MBB.
310     LocalValueMap[V] = Op0;
311   }
312   return true;
313 }
314
315 /// X86SelectStore - Select and emit code to implement store instructions.
316 bool X86FastISel::X86SelectStore(Instruction* I) {
317   MVT VT;
318   if (!isTypeLegal(I->getOperand(0)->getType(), TLI, VT))
319     return false;
320   unsigned Val = getRegForValue(I->getOperand(0));
321   if (Val == 0)
322     // Unhandled operand. Halt "fast" selection and bail.
323     return false;    
324
325   Value *V = I->getOperand(1);
326   unsigned Ptr = getRegForValue(V);
327   if (Ptr == 0) {
328     // Handle constant store address.
329     if (!isa<Constant>(V) || !X86SelectConstAddr(V, Ptr))
330       // Unhandled operand. Halt "fast" selection and bail.
331       return false;    
332   }
333
334   return X86FastEmitStore(VT, Val, Ptr, 0, V);
335 }
336
337 /// X86SelectLoad - Select and emit code to implement load instructions.
338 ///
339 bool X86FastISel::X86SelectLoad(Instruction *I)  {
340   MVT VT;
341   if (!isTypeLegal(I->getType(), TLI, VT))
342     return false;
343
344   Value *V = I->getOperand(0);
345   unsigned Ptr = getRegForValue(V);
346   if (Ptr == 0) {
347     // Handle constant load address.
348     // FIXME: If load type is something we can't handle, this can result in
349     // a dead stub load instruction.
350     if (!isa<Constant>(V) || !X86SelectConstAddr(V, Ptr))
351       // Unhandled operand. Halt "fast" selection and bail.
352       return false;    
353   }
354
355   unsigned ResultReg = 0;
356   if (X86FastEmitLoad(VT, Ptr, V, ResultReg)) {
357     UpdateValueMap(I, ResultReg);
358     return true;
359   }
360   return false;
361 }
362
363 bool X86FastISel::X86SelectCmp(Instruction *I) {
364   CmpInst *CI = cast<CmpInst>(I);
365
366   MVT VT = TLI.getValueType(I->getOperand(0)->getType());
367   if (!TLI.isTypeLegal(VT))
368     return false;
369
370   unsigned Op0Reg = getRegForValue(CI->getOperand(0));
371   if (Op0Reg == 0) return false;
372   unsigned Op1Reg = getRegForValue(CI->getOperand(1));
373   if (Op1Reg == 0) return false;
374
375   unsigned Opc;
376   switch (VT.getSimpleVT()) {
377   case MVT::i8: Opc = X86::CMP8rr; break;
378   case MVT::i16: Opc = X86::CMP16rr; break;
379   case MVT::i32: Opc = X86::CMP32rr; break;
380   case MVT::i64: Opc = X86::CMP64rr; break;
381   case MVT::f32: Opc = X86::UCOMISSrr; break;
382   case MVT::f64: Opc = X86::UCOMISDrr; break;
383   default: return false;
384   }
385
386   unsigned ResultReg = createResultReg(&X86::GR8RegClass);
387   switch (CI->getPredicate()) {
388   case CmpInst::FCMP_OEQ: {
389     unsigned EReg = createResultReg(&X86::GR8RegClass);
390     unsigned NPReg = createResultReg(&X86::GR8RegClass);
391     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
392     BuildMI(MBB, TII.get(X86::SETEr), EReg);
393     BuildMI(MBB, TII.get(X86::SETNPr), NPReg);
394     BuildMI(MBB, TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
395     break;
396   }
397   case CmpInst::FCMP_UNE: {
398     unsigned NEReg = createResultReg(&X86::GR8RegClass);
399     unsigned PReg = createResultReg(&X86::GR8RegClass);
400     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
401     BuildMI(MBB, TII.get(X86::SETNEr), NEReg);
402     BuildMI(MBB, TII.get(X86::SETPr), PReg);
403     BuildMI(MBB, TII.get(X86::OR8rr), ResultReg).addReg(PReg).addReg(NEReg);
404     break;
405   }
406   case CmpInst::FCMP_OGT:
407     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
408     BuildMI(MBB, TII.get(X86::SETAr), ResultReg);
409     break;
410   case CmpInst::FCMP_OGE:
411     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
412     BuildMI(MBB, TII.get(X86::SETAEr), ResultReg);
413     break;
414   case CmpInst::FCMP_OLT:
415     BuildMI(MBB, TII.get(Opc)).addReg(Op1Reg).addReg(Op0Reg);
416     BuildMI(MBB, TII.get(X86::SETAr), ResultReg);
417     break;
418   case CmpInst::FCMP_OLE:
419     BuildMI(MBB, TII.get(Opc)).addReg(Op1Reg).addReg(Op0Reg);
420     BuildMI(MBB, TII.get(X86::SETAEr), ResultReg);
421     break;
422   case CmpInst::FCMP_ONE:
423     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
424     BuildMI(MBB, TII.get(X86::SETNEr), ResultReg);
425     break;
426   case CmpInst::FCMP_ORD:
427     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
428     BuildMI(MBB, TII.get(X86::SETNPr), ResultReg);
429     break;
430   case CmpInst::FCMP_UNO:
431     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
432     BuildMI(MBB, TII.get(X86::SETPr), ResultReg);
433     break;
434   case CmpInst::FCMP_UEQ:
435     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
436     BuildMI(MBB, TII.get(X86::SETEr), ResultReg);
437     break;
438   case CmpInst::FCMP_UGT:
439     BuildMI(MBB, TII.get(Opc)).addReg(Op1Reg).addReg(Op0Reg);
440     BuildMI(MBB, TII.get(X86::SETBr), ResultReg);
441     break;
442   case CmpInst::FCMP_UGE:
443     BuildMI(MBB, TII.get(Opc)).addReg(Op1Reg).addReg(Op0Reg);
444     BuildMI(MBB, TII.get(X86::SETBEr), ResultReg);
445     break;
446   case CmpInst::FCMP_ULT:
447     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
448     BuildMI(MBB, TII.get(X86::SETBr), ResultReg);
449     break;
450   case CmpInst::FCMP_ULE:
451     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
452     BuildMI(MBB, TII.get(X86::SETBEr), ResultReg);
453     break;
454   case CmpInst::ICMP_EQ:
455     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
456     BuildMI(MBB, TII.get(X86::SETEr), ResultReg);
457     break;
458   case CmpInst::ICMP_NE:
459     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
460     BuildMI(MBB, TII.get(X86::SETNEr), ResultReg);
461     break;
462   case CmpInst::ICMP_UGT:
463     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
464     BuildMI(MBB, TII.get(X86::SETAr), ResultReg);
465     break;
466   case CmpInst::ICMP_UGE:
467     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
468     BuildMI(MBB, TII.get(X86::SETAEr), ResultReg);
469     break;
470   case CmpInst::ICMP_ULT:
471     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
472     BuildMI(MBB, TII.get(X86::SETBr), ResultReg);
473     break;
474   case CmpInst::ICMP_ULE:
475     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
476     BuildMI(MBB, TII.get(X86::SETBEr), ResultReg);
477     break;
478   case CmpInst::ICMP_SGT:
479     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
480     BuildMI(MBB, TII.get(X86::SETGr), ResultReg);
481     break;
482   case CmpInst::ICMP_SGE:
483     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
484     BuildMI(MBB, TII.get(X86::SETGEr), ResultReg);
485     break;
486   case CmpInst::ICMP_SLT:
487     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
488     BuildMI(MBB, TII.get(X86::SETLr), ResultReg);
489     break;
490   case CmpInst::ICMP_SLE:
491     BuildMI(MBB, TII.get(Opc)).addReg(Op0Reg).addReg(Op1Reg);
492     BuildMI(MBB, TII.get(X86::SETLEr), ResultReg);
493     break;
494   default:
495     return false;
496   }
497
498   UpdateValueMap(I, ResultReg);
499   return true;
500 }
501
502 bool X86FastISel::X86SelectZExt(Instruction *I) {
503   // Special-case hack: The only i1 values we know how to produce currently
504   // set the upper bits of an i8 value to zero.
505   if (I->getType() == Type::Int8Ty &&
506       I->getOperand(0)->getType() == Type::Int1Ty) {
507     unsigned ResultReg = getRegForValue(I->getOperand(0));
508     if (ResultReg == 0) return false;
509     UpdateValueMap(I, ResultReg);
510     return true;
511   }
512
513   return false;
514 }
515
516 bool X86FastISel::X86SelectBranch(Instruction *I) {
517   BranchInst *BI = cast<BranchInst>(I);
518   // Unconditional branches are selected by tablegen-generated code.
519   unsigned OpReg = getRegForValue(BI->getCondition());
520   if (OpReg == 0) return false;
521   MachineBasicBlock *TrueMBB = MBBMap[BI->getSuccessor(0)];
522   MachineBasicBlock *FalseMBB = MBBMap[BI->getSuccessor(1)];
523
524   BuildMI(MBB, TII.get(X86::TEST8rr)).addReg(OpReg).addReg(OpReg);
525   BuildMI(MBB, TII.get(X86::JNE)).addMBB(TrueMBB);
526   BuildMI(MBB, TII.get(X86::JMP)).addMBB(FalseMBB);
527
528   MBB->addSuccessor(TrueMBB);
529   MBB->addSuccessor(FalseMBB);
530
531   return true;
532 }
533
534 bool X86FastISel::X86SelectShift(Instruction *I) {
535   unsigned CReg = 0;
536   unsigned Opc = 0;
537   const TargetRegisterClass *RC = NULL;
538   if (I->getType() == Type::Int8Ty) {
539     CReg = X86::CL;
540     RC = &X86::GR8RegClass;
541     switch (I->getOpcode()) {
542     case Instruction::LShr: Opc = X86::SHR8rCL; break;
543     case Instruction::AShr: Opc = X86::SAR8rCL; break;
544     case Instruction::Shl:  Opc = X86::SHL8rCL; break;
545     default: return false;
546     }
547   } else if (I->getType() == Type::Int16Ty) {
548     CReg = X86::CX;
549     RC = &X86::GR16RegClass;
550     switch (I->getOpcode()) {
551     case Instruction::LShr: Opc = X86::SHR16rCL; break;
552     case Instruction::AShr: Opc = X86::SAR16rCL; break;
553     case Instruction::Shl:  Opc = X86::SHL16rCL; break;
554     default: return false;
555     }
556   } else if (I->getType() == Type::Int32Ty) {
557     CReg = X86::ECX;
558     RC = &X86::GR32RegClass;
559     switch (I->getOpcode()) {
560     case Instruction::LShr: Opc = X86::SHR32rCL; break;
561     case Instruction::AShr: Opc = X86::SAR32rCL; break;
562     case Instruction::Shl:  Opc = X86::SHL32rCL; break;
563     default: return false;
564     }
565   } else if (I->getType() == Type::Int64Ty) {
566     CReg = X86::RCX;
567     RC = &X86::GR64RegClass;
568     switch (I->getOpcode()) {
569     case Instruction::LShr: Opc = X86::SHR64rCL; break;
570     case Instruction::AShr: Opc = X86::SAR64rCL; break;
571     case Instruction::Shl:  Opc = X86::SHL64rCL; break;
572     default: return false;
573     }
574   } else {
575     return false;
576   }
577
578   MVT VT = MVT::getMVT(I->getType(), /*HandleUnknown=*/true);
579   if (VT == MVT::Other || !TLI.isTypeLegal(VT))
580     return false;
581
582   unsigned Op0Reg = getRegForValue(I->getOperand(0));
583   if (Op0Reg == 0) return false;
584   unsigned Op1Reg = getRegForValue(I->getOperand(1));
585   if (Op1Reg == 0) return false;
586   TII.copyRegToReg(*MBB, MBB->end(), CReg, Op1Reg, RC, RC);
587   unsigned ResultReg = createResultReg(RC);
588   BuildMI(MBB, TII.get(Opc), ResultReg).addReg(Op0Reg);
589   UpdateValueMap(I, ResultReg);
590   return true;
591 }
592
593 bool X86FastISel::X86SelectSelect(Instruction *I) {
594   const Type *Ty = I->getType();
595   if (isa<PointerType>(Ty))
596     Ty = TLI.getTargetData()->getIntPtrType();
597
598   unsigned Opc = 0;
599   const TargetRegisterClass *RC = NULL;
600   if (Ty == Type::Int16Ty) {
601     Opc = X86::CMOVE16rr;
602     RC = &X86::GR16RegClass;
603   } else if (Ty == Type::Int32Ty) {
604     Opc = X86::CMOVE32rr;
605     RC = &X86::GR32RegClass;
606   } else if (Ty == Type::Int64Ty) {
607     Opc = X86::CMOVE64rr;
608     RC = &X86::GR64RegClass;
609   } else {
610     return false; 
611   }
612
613   MVT VT = MVT::getMVT(Ty, /*HandleUnknown=*/true);
614   if (VT == MVT::Other || !TLI.isTypeLegal(VT))
615     return false;
616
617   unsigned Op0Reg = getRegForValue(I->getOperand(0));
618   if (Op0Reg == 0) return false;
619   unsigned Op1Reg = getRegForValue(I->getOperand(1));
620   if (Op1Reg == 0) return false;
621   unsigned Op2Reg = getRegForValue(I->getOperand(2));
622   if (Op2Reg == 0) return false;
623
624   BuildMI(MBB, TII.get(X86::TEST8rr)).addReg(Op0Reg).addReg(Op0Reg);
625   unsigned ResultReg = createResultReg(RC);
626   BuildMI(MBB, TII.get(Opc), ResultReg).addReg(Op1Reg).addReg(Op2Reg);
627   UpdateValueMap(I, ResultReg);
628   return true;
629 }
630
631 bool X86FastISel::X86SelectTrunc(Instruction *I) {
632   if (Subtarget->is64Bit())
633     // All other cases should be handled by the tblgen generated code.
634     return false;
635   MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
636   MVT DstVT = TLI.getValueType(I->getType());
637   if (DstVT != MVT::i8)
638     // All other cases should be handled by the tblgen generated code.
639     return false;
640   if (SrcVT != MVT::i16 && SrcVT != MVT::i32)
641     // All other cases should be handled by the tblgen generated code.
642     return false;
643
644   unsigned InputReg = getRegForValue(I->getOperand(0));
645   if (!InputReg)
646     // Unhandled operand.  Halt "fast" selection and bail.
647     return false;
648
649   // First issue a copy to GR16_ or GR32_.
650   unsigned CopyOpc = (SrcVT == MVT::i16) ? X86::MOV16to16_ : X86::MOV32to32_;
651   const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
652     ? X86::GR16_RegisterClass : X86::GR32_RegisterClass;
653   unsigned CopyReg = createResultReg(CopyRC);
654   BuildMI(MBB, TII.get(CopyOpc), CopyReg).addReg(InputReg);
655
656   // Then issue an extract_subreg.
657   unsigned ResultReg = FastEmitInst_extractsubreg(CopyReg,1); // x86_subreg_8bit
658   if (!ResultReg)
659     return false;
660
661   UpdateValueMap(I, ResultReg);
662   return true;
663 }
664
665 bool X86FastISel::X86SelectCall(Instruction *I) {
666   CallInst *CI = cast<CallInst>(I);
667   Value *Callee = I->getOperand(0);
668
669   // Can't handle inline asm yet.
670   if (isa<InlineAsm>(Callee))
671     return false;
672
673   // FIXME: Handle some intrinsics.
674   if (Function *F = CI->getCalledFunction()) {
675     if (F->isDeclaration() &&F->getIntrinsicID())
676       return false;
677   }
678
679   // Materialize callee address in a register. FIXME: GV address can be
680   // handled with a CALLpcrel32 instead.
681   unsigned CalleeOp = getRegForValue(Callee);
682   if (CalleeOp == 0) {
683     if (!isa<Constant>(Callee) || !X86SelectConstAddr(Callee, CalleeOp, true))
684       // Unhandled operand. Halt "fast" selection and bail.
685       return false;    
686   }
687
688   // Handle only C and fastcc calling conventions for now.
689   CallSite CS(CI);
690   unsigned CC = CS.getCallingConv();
691   if (CC != CallingConv::C &&
692       CC != CallingConv::Fast &&
693       CC != CallingConv::X86_FastCall)
694     return false;
695
696   // Let SDISel handle vararg functions.
697   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
698   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
699   if (FTy->isVarArg())
700     return false;
701
702   // Handle *simple* calls for now.
703   const Type *RetTy = CS.getType();
704   MVT RetVT;
705   if (!isTypeLegal(RetTy, TLI, RetVT, true))
706     return false;
707
708   // Allow calls which produce i1 results.
709   bool AndToI1 = false;
710   if (RetVT == MVT::i1) {
711     RetVT = MVT::i8;
712     AndToI1 = true;
713   }
714
715   // Deal with call operands first.
716   SmallVector<unsigned, 4> Args;
717   SmallVector<MVT, 4> ArgVTs;
718   SmallVector<ISD::ArgFlagsTy, 4> ArgFlags;
719   Args.reserve(CS.arg_size());
720   ArgVTs.reserve(CS.arg_size());
721   ArgFlags.reserve(CS.arg_size());
722   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
723        i != e; ++i) {
724     unsigned Arg = getRegForValue(*i);
725     if (Arg == 0)
726       return false;
727     ISD::ArgFlagsTy Flags;
728     unsigned AttrInd = i - CS.arg_begin() + 1;
729     if (CS.paramHasAttr(AttrInd, ParamAttr::SExt))
730       Flags.setSExt();
731     if (CS.paramHasAttr(AttrInd, ParamAttr::ZExt))
732       Flags.setZExt();
733
734     // FIXME: Only handle *easy* calls for now.
735     if (CS.paramHasAttr(AttrInd, ParamAttr::InReg) ||
736         CS.paramHasAttr(AttrInd, ParamAttr::StructRet) ||
737         CS.paramHasAttr(AttrInd, ParamAttr::Nest) ||
738         CS.paramHasAttr(AttrInd, ParamAttr::ByVal))
739       return false;
740
741     const Type *ArgTy = (*i)->getType();
742     MVT ArgVT;
743     if (!isTypeLegal(ArgTy, TLI, ArgVT))
744       return false;
745     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
746     Flags.setOrigAlign(OriginalAlignment);
747
748     Args.push_back(Arg);
749     ArgVTs.push_back(ArgVT);
750     ArgFlags.push_back(Flags);
751   }
752
753   // Analyze operands of the call, assigning locations to each operand.
754   SmallVector<CCValAssign, 16> ArgLocs;
755   CCState CCInfo(CC, false, TM, ArgLocs);
756   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
757
758   // Get a count of how many bytes are to be pushed on the stack.
759   unsigned NumBytes = CCInfo.getNextStackOffset();
760
761   // Issue CALLSEQ_START
762   BuildMI(MBB, TII.get(X86::ADJCALLSTACKDOWN)).addImm(NumBytes);
763
764   // Process argumenet: walk the register/memloc assignments, inserting
765   // copies / loads.
766   SmallVector<unsigned, 4> RegArgs;
767   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
768     CCValAssign &VA = ArgLocs[i];
769     unsigned Arg = Args[VA.getValNo()];
770     MVT ArgVT = ArgVTs[VA.getValNo()];
771   
772     // Promote the value if needed.
773     switch (VA.getLocInfo()) {
774     default: assert(0 && "Unknown loc info!");
775     case CCValAssign::Full: break;
776     case CCValAssign::SExt: {
777       bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
778                                        Arg, ArgVT, Arg);
779       assert(Emitted && "Failed to emit a sext!");
780       ArgVT = VA.getLocVT();
781       break;
782     }
783     case CCValAssign::ZExt: {
784       bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
785                                        Arg, ArgVT, Arg);
786       assert(Emitted && "Failed to emit a zext!");
787       ArgVT = VA.getLocVT();
788       break;
789     }
790     case CCValAssign::AExt: {
791       bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
792                                        Arg, ArgVT, Arg);
793       assert(Emitted && "Failed to emit a aext!");
794       ArgVT = VA.getLocVT();
795       break;
796     }
797     }
798     
799     if (VA.isRegLoc()) {
800       TargetRegisterClass* RC = TLI.getRegClassFor(ArgVT);
801       bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), VA.getLocReg(),
802                                       Arg, RC, RC);
803       assert(Emitted && "Failed to emit a copy instruction!");
804       RegArgs.push_back(VA.getLocReg());
805     } else {
806       unsigned LocMemOffset = VA.getLocMemOffset();
807       X86FastEmitStore(ArgVT, Arg, StackPtr, LocMemOffset, NULL);
808     }
809   }
810
811   // Issue the call.
812   unsigned CallOpc = CalleeOp
813     ? (Subtarget->is64Bit() ? X86::CALL64r       : X86::CALL32r)
814     : (Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32);
815   MachineInstrBuilder MIB = CalleeOp
816     ? BuildMI(MBB, TII.get(CallOpc)).addReg(CalleeOp)
817     :BuildMI(MBB, TII.get(CallOpc)).addGlobalAddress(cast<GlobalValue>(Callee));
818   // Add implicit physical register uses to the call.
819   while (!RegArgs.empty()) {
820     MIB.addReg(RegArgs.back());
821     RegArgs.pop_back();
822   }
823
824   // Issue CALLSEQ_END
825   BuildMI(MBB, TII.get(X86::ADJCALLSTACKUP)).addImm(NumBytes).addImm(0);
826
827   // Now handle call return value (if any).
828   if (RetVT.getSimpleVT() != MVT::isVoid) {
829     SmallVector<CCValAssign, 16> RVLocs;
830     CCState CCInfo(CC, false, TM, RVLocs);
831     CCInfo.AnalyzeCallResult(RetVT, RetCC_X86);
832
833     // Copy all of the result registers out of their specified physreg.
834     assert(RVLocs.size() == 1 && "Can't handle multi-value calls!");
835     MVT CopyVT = RVLocs[0].getValVT();
836     TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
837     TargetRegisterClass *SrcRC = DstRC;
838     
839     // If this is a call to a function that returns an fp value on the x87 fp
840     // stack, but where we prefer to use the value in xmm registers, copy it
841     // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
842     if ((RVLocs[0].getLocReg() == X86::ST0 ||
843          RVLocs[0].getLocReg() == X86::ST1) &&
844         isScalarFPTypeInSSEReg(RVLocs[0].getValVT())) {
845       CopyVT = MVT::f80;
846       SrcRC = X86::RSTRegisterClass;
847       DstRC = X86::RFP80RegisterClass;
848     }
849
850     unsigned ResultReg = createResultReg(DstRC);
851     bool Emitted = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
852                                     RVLocs[0].getLocReg(), DstRC, SrcRC);
853     assert(Emitted && "Failed to emit a copy instruction!");
854     if (CopyVT != RVLocs[0].getValVT()) {
855       // Round the F80 the right size, which also moves to the appropriate xmm
856       // register. This is accomplished by storing the F80 value in memory and
857       // then loading it back. Ewww...
858       MVT ResVT = RVLocs[0].getValVT();
859       unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
860       unsigned MemSize = ResVT.getSizeInBits()/8;
861       int FI = MFI->CreateStackObject(MemSize, MemSize);
862       addFrameReference(BuildMI(MBB, TII.get(Opc)), FI).addReg(ResultReg);
863       DstRC = ResVT == MVT::f32
864         ? X86::FR32RegisterClass : X86::FR64RegisterClass;
865       Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
866       ResultReg = createResultReg(DstRC);
867       addFrameReference(BuildMI(MBB, TII.get(Opc), ResultReg), FI);
868     }
869
870     if (AndToI1) {
871       // Mask out all but lowest bit for some call which produces an i1.
872       unsigned AndResult = createResultReg(X86::GR8RegisterClass);
873       BuildMI(MBB, TII.get(X86::AND8ri), AndResult).addReg(ResultReg).addImm(1);
874       ResultReg = AndResult;
875     }
876
877     UpdateValueMap(I, ResultReg);
878   }
879
880   return true;
881 }
882
883
884 bool
885 X86FastISel::TargetSelectInstruction(Instruction *I)  {
886   switch (I->getOpcode()) {
887   default: break;
888   case Instruction::Load:
889     return X86SelectLoad(I);
890   case Instruction::Store:
891     return X86SelectStore(I);
892   case Instruction::ICmp:
893   case Instruction::FCmp:
894     return X86SelectCmp(I);
895   case Instruction::ZExt:
896     return X86SelectZExt(I);
897   case Instruction::Br:
898     return X86SelectBranch(I);
899   case Instruction::Call:
900     return X86SelectCall(I);
901   case Instruction::LShr:
902   case Instruction::AShr:
903   case Instruction::Shl:
904     return X86SelectShift(I);
905   case Instruction::Select:
906     return X86SelectSelect(I);
907   case Instruction::Trunc:
908     return X86SelectTrunc(I);
909   }
910
911   return false;
912 }
913
914 unsigned X86FastISel::TargetMaterializeConstant(Constant *C,
915                                                 MachineConstantPool* MCP) {
916   // Can't handle PIC-mode yet.
917   if (TM.getRelocationModel() == Reloc::PIC_)
918     return 0;
919   
920   MVT VT = MVT::getMVT(C->getType(), /*HandleUnknown=*/true);
921   if (VT == MVT::Other || !VT.isSimple())
922     // Unhandled type. Halt "fast" selection and bail.
923     return false;
924   if (VT == MVT::iPTR)
925     // Use pointer type.
926     VT = TLI.getPointerTy();
927   // We only handle legal types. For example, on x86-32 the instruction
928   // selector contains all of the 64-bit instructions from x86-64,
929   // under the assumption that i64 won't be used if the target doesn't
930   // support it.
931   if (!TLI.isTypeLegal(VT))
932     return false;
933   
934   // Get opcode and regclass of the output for the given load instruction.
935   unsigned Opc = 0;
936   const TargetRegisterClass *RC = NULL;
937   switch (VT.getSimpleVT()) {
938   default: return false;
939   case MVT::i8:
940     Opc = X86::MOV8rm;
941     RC  = X86::GR8RegisterClass;
942     break;
943   case MVT::i16:
944     Opc = X86::MOV16rm;
945     RC  = X86::GR16RegisterClass;
946     break;
947   case MVT::i32:
948     Opc = X86::MOV32rm;
949     RC  = X86::GR32RegisterClass;
950     break;
951   case MVT::i64:
952     // Must be in x86-64 mode.
953     Opc = X86::MOV64rm;
954     RC  = X86::GR64RegisterClass;
955     break;
956   case MVT::f32:
957     if (Subtarget->hasSSE1()) {
958       Opc = X86::MOVSSrm;
959       RC  = X86::FR32RegisterClass;
960     } else {
961       Opc = X86::LD_Fp32m;
962       RC  = X86::RFP32RegisterClass;
963     }
964     break;
965   case MVT::f64:
966     if (Subtarget->hasSSE2()) {
967       Opc = X86::MOVSDrm;
968       RC  = X86::FR64RegisterClass;
969     } else {
970       Opc = X86::LD_Fp64m;
971       RC  = X86::RFP64RegisterClass;
972     }
973     break;
974   case MVT::f80:
975     Opc = X86::LD_Fp80m;
976     RC  = X86::RFP80RegisterClass;
977     break;
978   }
979   
980   unsigned ResultReg = createResultReg(RC);
981   if (isa<GlobalValue>(C)) {
982     // FIXME: If store value type is something we can't handle, this can result
983     // in a dead stub load instruction.
984     if (X86SelectConstAddr(C, ResultReg))
985       return ResultReg;
986     return 0;
987   }
988   
989   // MachineConstantPool wants an explicit alignment.
990   unsigned Align =
991                TM.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
992   if (Align == 0) {
993     // Alignment of vector types.  FIXME!
994     Align = TM.getTargetData()->getABITypeSize(C->getType());
995     Align = Log2_64(Align);
996   }
997   
998   unsigned MCPOffset = MCP->getConstantPoolIndex(C, Align);
999   addConstantPoolReference(BuildMI(MBB, TII.get(Opc), ResultReg), MCPOffset);
1000   return ResultReg;
1001 }
1002
1003 namespace llvm {
1004   llvm::FastISel *X86::createFastISel(MachineFunction &mf,
1005                         DenseMap<const Value *, unsigned> &vm,
1006                         DenseMap<const BasicBlock *, MachineBasicBlock *> &bm) {
1007     return new X86FastISel(mf, vm, bm);
1008   }
1009 }