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