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