[FastISel][X86] Refactor the code to get the X86 condition from a helper function...
[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 "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86InstrInfo.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86RegisterInfo.h"
22 #include "X86Subtarget.h"
23 #include "X86TargetMachine.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/IR/CallSite.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/GetElementPtrTypeIterator.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Target/TargetOptions.h"
42 using namespace llvm;
43
44 namespace {
45
46 class X86FastISel final : public FastISel {
47   /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
48   /// make the right decision when generating code for different targets.
49   const X86Subtarget *Subtarget;
50
51   /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
52   /// floating point ops.
53   /// When SSE is available, use it for f32 operations.
54   /// When SSE2 is available, use it for f64 operations.
55   bool X86ScalarSSEf64;
56   bool X86ScalarSSEf32;
57
58 public:
59   explicit X86FastISel(FunctionLoweringInfo &funcInfo,
60                        const TargetLibraryInfo *libInfo)
61     : FastISel(funcInfo, libInfo) {
62     Subtarget = &TM.getSubtarget<X86Subtarget>();
63     X86ScalarSSEf64 = Subtarget->hasSSE2();
64     X86ScalarSSEf32 = Subtarget->hasSSE1();
65   }
66
67   bool TargetSelectInstruction(const Instruction *I) override;
68
69   /// \brief The specified machine instr operand is a vreg, and that
70   /// vreg is being provided by the specified load instruction.  If possible,
71   /// try to fold the load as an operand to the instruction, returning true if
72   /// possible.
73   bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
74                            const LoadInst *LI) override;
75
76   bool FastLowerArguments() override;
77
78 #include "X86GenFastISel.inc"
79
80 private:
81   bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
82
83   bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO,
84                        unsigned &ResultReg);
85
86   bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
87                         MachineMemOperand *MMO = nullptr, bool Aligned = false);
88   bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
89                         const X86AddressMode &AM,
90                         MachineMemOperand *MMO = nullptr, bool Aligned = false);
91
92   bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
93                          unsigned &ResultReg);
94
95   bool X86SelectAddress(const Value *V, X86AddressMode &AM);
96   bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
97
98   bool X86SelectLoad(const Instruction *I);
99
100   bool X86SelectStore(const Instruction *I);
101
102   bool X86SelectRet(const Instruction *I);
103
104   bool X86SelectCmp(const Instruction *I);
105
106   bool X86SelectZExt(const Instruction *I);
107
108   bool X86SelectBranch(const Instruction *I);
109
110   bool X86SelectShift(const Instruction *I);
111
112   bool X86SelectDivRem(const Instruction *I);
113
114   bool X86SelectSelect(const Instruction *I);
115
116   bool X86SelectTrunc(const Instruction *I);
117
118   bool X86SelectFPExt(const Instruction *I);
119   bool X86SelectFPTrunc(const Instruction *I);
120
121   bool X86VisitIntrinsicCall(const IntrinsicInst &I);
122   bool X86SelectCall(const Instruction *I);
123
124   bool DoSelectCall(const Instruction *I, const char *MemIntName);
125
126   const X86InstrInfo *getInstrInfo() const {
127     return getTargetMachine()->getInstrInfo();
128   }
129   const X86TargetMachine *getTargetMachine() const {
130     return static_cast<const X86TargetMachine *>(&TM);
131   }
132
133   bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
134
135   unsigned TargetMaterializeConstant(const Constant *C) override;
136
137   unsigned TargetMaterializeAlloca(const AllocaInst *C) override;
138
139   unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override;
140
141   /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
142   /// computed in an SSE register, not on the X87 floating point stack.
143   bool isScalarFPTypeInSSEReg(EVT VT) const {
144     return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
145       (VT == MVT::f32 && X86ScalarSSEf32);   // f32 is when SSE1
146   }
147
148   bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
149
150   bool IsMemcpySmall(uint64_t Len);
151
152   bool TryEmitSmallMemcpy(X86AddressMode DestAM,
153                           X86AddressMode SrcAM, uint64_t Len);
154 };
155
156 } // end anonymous namespace.
157
158 static std::pair<X86::CondCode, bool>
159 getX86ConditonCode(CmpInst::Predicate Predicate) {
160   X86::CondCode CC = X86::COND_INVALID;
161   bool NeedSwap = false;
162   switch (Predicate) {
163   default: break;
164   // Floating-point Predicates
165   case CmpInst::FCMP_UEQ: CC = X86::COND_E;       break;
166   case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
167   case CmpInst::FCMP_OGT: CC = X86::COND_A;       break;
168   case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
169   case CmpInst::FCMP_OGE: CC = X86::COND_AE;      break;
170   case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
171   case CmpInst::FCMP_ULT: CC = X86::COND_B;       break;
172   case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
173   case CmpInst::FCMP_ULE: CC = X86::COND_BE;      break;
174   case CmpInst::FCMP_ONE: CC = X86::COND_NE;      break;
175   case CmpInst::FCMP_UNO: CC = X86::COND_P;       break;
176   case CmpInst::FCMP_ORD: CC = X86::COND_NP;      break;
177   case CmpInst::FCMP_OEQ: // fall-through
178   case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
179
180   // Integer Predicates
181   case CmpInst::ICMP_EQ:  CC = X86::COND_E;       break;
182   case CmpInst::ICMP_NE:  CC = X86::COND_NE;      break;
183   case CmpInst::ICMP_UGT: CC = X86::COND_A;       break;
184   case CmpInst::ICMP_UGE: CC = X86::COND_AE;      break;
185   case CmpInst::ICMP_ULT: CC = X86::COND_B;       break;
186   case CmpInst::ICMP_ULE: CC = X86::COND_BE;      break;
187   case CmpInst::ICMP_SGT: CC = X86::COND_G;       break;
188   case CmpInst::ICMP_SGE: CC = X86::COND_GE;      break;
189   case CmpInst::ICMP_SLT: CC = X86::COND_L;       break;
190   case CmpInst::ICMP_SLE: CC = X86::COND_LE;      break;
191   }
192
193   return std::make_pair(CC, NeedSwap);
194 }
195
196 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
197   EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
198   if (evt == MVT::Other || !evt.isSimple())
199     // Unhandled type. Halt "fast" selection and bail.
200     return false;
201
202   VT = evt.getSimpleVT();
203   // For now, require SSE/SSE2 for performing floating-point operations,
204   // since x87 requires additional work.
205   if (VT == MVT::f64 && !X86ScalarSSEf64)
206     return false;
207   if (VT == MVT::f32 && !X86ScalarSSEf32)
208     return false;
209   // Similarly, no f80 support yet.
210   if (VT == MVT::f80)
211     return false;
212   // We only handle legal types. For example, on x86-32 the instruction
213   // selector contains all of the 64-bit instructions from x86-64,
214   // under the assumption that i64 won't be used if the target doesn't
215   // support it.
216   return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
217 }
218
219 #include "X86GenCallingConv.inc"
220
221 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
222 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
223 /// Return true and the result register by reference if it is possible.
224 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
225                                   MachineMemOperand *MMO, unsigned &ResultReg) {
226   // Get opcode and regclass of the output for the given load instruction.
227   unsigned Opc = 0;
228   const TargetRegisterClass *RC = nullptr;
229   switch (VT.getSimpleVT().SimpleTy) {
230   default: return false;
231   case MVT::i1:
232   case MVT::i8:
233     Opc = X86::MOV8rm;
234     RC  = &X86::GR8RegClass;
235     break;
236   case MVT::i16:
237     Opc = X86::MOV16rm;
238     RC  = &X86::GR16RegClass;
239     break;
240   case MVT::i32:
241     Opc = X86::MOV32rm;
242     RC  = &X86::GR32RegClass;
243     break;
244   case MVT::i64:
245     // Must be in x86-64 mode.
246     Opc = X86::MOV64rm;
247     RC  = &X86::GR64RegClass;
248     break;
249   case MVT::f32:
250     if (X86ScalarSSEf32) {
251       Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
252       RC  = &X86::FR32RegClass;
253     } else {
254       Opc = X86::LD_Fp32m;
255       RC  = &X86::RFP32RegClass;
256     }
257     break;
258   case MVT::f64:
259     if (X86ScalarSSEf64) {
260       Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
261       RC  = &X86::FR64RegClass;
262     } else {
263       Opc = X86::LD_Fp64m;
264       RC  = &X86::RFP64RegClass;
265     }
266     break;
267   case MVT::f80:
268     // No f80 support yet.
269     return false;
270   }
271
272   ResultReg = createResultReg(RC);
273   MachineInstrBuilder MIB =
274     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
275   addFullAddress(MIB, AM);
276   if (MMO)
277     MIB->addMemOperand(*FuncInfo.MF, MMO);
278   return true;
279 }
280
281 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
282 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
283 /// and a displacement offset, or a GlobalAddress,
284 /// i.e. V. Return true if it is possible.
285 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
286                                    const X86AddressMode &AM,
287                                    MachineMemOperand *MMO, bool Aligned) {
288   // Get opcode and regclass of the output for the given store instruction.
289   unsigned Opc = 0;
290   switch (VT.getSimpleVT().SimpleTy) {
291   case MVT::f80: // No f80 support yet.
292   default: return false;
293   case MVT::i1: {
294     // Mask out all but lowest bit.
295     unsigned AndResult = createResultReg(&X86::GR8RegClass);
296     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
297             TII.get(X86::AND8ri), AndResult)
298       .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
299     ValReg = AndResult;
300   }
301   // FALLTHROUGH, handling i1 as i8.
302   case MVT::i8:  Opc = X86::MOV8mr;  break;
303   case MVT::i16: Opc = X86::MOV16mr; break;
304   case MVT::i32: Opc = X86::MOV32mr; break;
305   case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
306   case MVT::f32:
307     Opc = X86ScalarSSEf32 ?
308           (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
309     break;
310   case MVT::f64:
311     Opc = X86ScalarSSEf64 ?
312           (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
313     break;
314   case MVT::v4f32:
315     if (Aligned)
316       Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
317     else
318       Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
319     break;
320   case MVT::v2f64:
321     if (Aligned)
322       Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
323     else
324       Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
325     break;
326   case MVT::v4i32:
327   case MVT::v2i64:
328   case MVT::v8i16:
329   case MVT::v16i8:
330     if (Aligned)
331       Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
332     else
333       Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
334     break;
335   }
336
337   MachineInstrBuilder MIB =
338     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
339   addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
340   if (MMO)
341     MIB->addMemOperand(*FuncInfo.MF, MMO);
342
343   return true;
344 }
345
346 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
347                                    const X86AddressMode &AM,
348                                    MachineMemOperand *MMO, bool Aligned) {
349   // Handle 'null' like i32/i64 0.
350   if (isa<ConstantPointerNull>(Val))
351     Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
352
353   // If this is a store of a simple constant, fold the constant into the store.
354   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
355     unsigned Opc = 0;
356     bool Signed = true;
357     switch (VT.getSimpleVT().SimpleTy) {
358     default: break;
359     case MVT::i1:  Signed = false;     // FALLTHROUGH to handle as i8.
360     case MVT::i8:  Opc = X86::MOV8mi;  break;
361     case MVT::i16: Opc = X86::MOV16mi; break;
362     case MVT::i32: Opc = X86::MOV32mi; break;
363     case MVT::i64:
364       // Must be a 32-bit sign extended value.
365       if (isInt<32>(CI->getSExtValue()))
366         Opc = X86::MOV64mi32;
367       break;
368     }
369
370     if (Opc) {
371       MachineInstrBuilder MIB =
372         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
373       addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
374                                             : CI->getZExtValue());
375       if (MMO)
376         MIB->addMemOperand(*FuncInfo.MF, MMO);
377       return true;
378     }
379   }
380
381   unsigned ValReg = getRegForValue(Val);
382   if (ValReg == 0)
383     return false;
384
385   bool ValKill = hasTrivialKill(Val);
386   return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
387 }
388
389 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
390 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
391 /// ISD::SIGN_EXTEND).
392 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
393                                     unsigned Src, EVT SrcVT,
394                                     unsigned &ResultReg) {
395   unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
396                            Src, /*TODO: Kill=*/false);
397   if (RR == 0)
398     return false;
399
400   ResultReg = RR;
401   return true;
402 }
403
404 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
405   // Handle constant address.
406   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
407     // Can't handle alternate code models yet.
408     if (TM.getCodeModel() != CodeModel::Small)
409       return false;
410
411     // Can't handle TLS yet.
412     if (GV->isThreadLocal())
413       return false;
414
415     // RIP-relative addresses can't have additional register operands, so if
416     // we've already folded stuff into the addressing mode, just force the
417     // global value into its own register, which we can use as the basereg.
418     if (!Subtarget->isPICStyleRIPRel() ||
419         (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
420       // Okay, we've committed to selecting this global. Set up the address.
421       AM.GV = GV;
422
423       // Allow the subtarget to classify the global.
424       unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
425
426       // If this reference is relative to the pic base, set it now.
427       if (isGlobalRelativeToPICBase(GVFlags)) {
428         // FIXME: How do we know Base.Reg is free??
429         AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
430       }
431
432       // Unless the ABI requires an extra load, return a direct reference to
433       // the global.
434       if (!isGlobalStubReference(GVFlags)) {
435         if (Subtarget->isPICStyleRIPRel()) {
436           // Use rip-relative addressing if we can.  Above we verified that the
437           // base and index registers are unused.
438           assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
439           AM.Base.Reg = X86::RIP;
440         }
441         AM.GVOpFlags = GVFlags;
442         return true;
443       }
444
445       // Ok, we need to do a load from a stub.  If we've already loaded from
446       // this stub, reuse the loaded pointer, otherwise emit the load now.
447       DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
448       unsigned LoadReg;
449       if (I != LocalValueMap.end() && I->second != 0) {
450         LoadReg = I->second;
451       } else {
452         // Issue load from stub.
453         unsigned Opc = 0;
454         const TargetRegisterClass *RC = nullptr;
455         X86AddressMode StubAM;
456         StubAM.Base.Reg = AM.Base.Reg;
457         StubAM.GV = GV;
458         StubAM.GVOpFlags = GVFlags;
459
460         // Prepare for inserting code in the local-value area.
461         SavePoint SaveInsertPt = enterLocalValueArea();
462
463         if (TLI.getPointerTy() == MVT::i64) {
464           Opc = X86::MOV64rm;
465           RC  = &X86::GR64RegClass;
466
467           if (Subtarget->isPICStyleRIPRel())
468             StubAM.Base.Reg = X86::RIP;
469         } else {
470           Opc = X86::MOV32rm;
471           RC  = &X86::GR32RegClass;
472         }
473
474         LoadReg = createResultReg(RC);
475         MachineInstrBuilder LoadMI =
476           BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
477         addFullAddress(LoadMI, StubAM);
478
479         // Ok, back to normal mode.
480         leaveLocalValueArea(SaveInsertPt);
481
482         // Prevent loading GV stub multiple times in same MBB.
483         LocalValueMap[V] = LoadReg;
484       }
485
486       // Now construct the final address. Note that the Disp, Scale,
487       // and Index values may already be set here.
488       AM.Base.Reg = LoadReg;
489       AM.GV = nullptr;
490       return true;
491     }
492   }
493
494   // If all else fails, try to materialize the value in a register.
495   if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
496     if (AM.Base.Reg == 0) {
497       AM.Base.Reg = getRegForValue(V);
498       return AM.Base.Reg != 0;
499     }
500     if (AM.IndexReg == 0) {
501       assert(AM.Scale == 1 && "Scale with no index!");
502       AM.IndexReg = getRegForValue(V);
503       return AM.IndexReg != 0;
504     }
505   }
506
507   return false;
508 }
509
510 /// X86SelectAddress - Attempt to fill in an address from the given value.
511 ///
512 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
513   SmallVector<const Value *, 32> GEPs;
514 redo_gep:
515   const User *U = nullptr;
516   unsigned Opcode = Instruction::UserOp1;
517   if (const Instruction *I = dyn_cast<Instruction>(V)) {
518     // Don't walk into other basic blocks; it's possible we haven't
519     // visited them yet, so the instructions may not yet be assigned
520     // virtual registers.
521     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
522         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
523       Opcode = I->getOpcode();
524       U = I;
525     }
526   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
527     Opcode = C->getOpcode();
528     U = C;
529   }
530
531   if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
532     if (Ty->getAddressSpace() > 255)
533       // Fast instruction selection doesn't support the special
534       // address spaces.
535       return false;
536
537   switch (Opcode) {
538   default: break;
539   case Instruction::BitCast:
540     // Look past bitcasts.
541     return X86SelectAddress(U->getOperand(0), AM);
542
543   case Instruction::IntToPtr:
544     // Look past no-op inttoptrs.
545     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
546       return X86SelectAddress(U->getOperand(0), AM);
547     break;
548
549   case Instruction::PtrToInt:
550     // Look past no-op ptrtoints.
551     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
552       return X86SelectAddress(U->getOperand(0), AM);
553     break;
554
555   case Instruction::Alloca: {
556     // Do static allocas.
557     const AllocaInst *A = cast<AllocaInst>(V);
558     DenseMap<const AllocaInst*, int>::iterator SI =
559       FuncInfo.StaticAllocaMap.find(A);
560     if (SI != FuncInfo.StaticAllocaMap.end()) {
561       AM.BaseType = X86AddressMode::FrameIndexBase;
562       AM.Base.FrameIndex = SI->second;
563       return true;
564     }
565     break;
566   }
567
568   case Instruction::Add: {
569     // Adds of constants are common and easy enough.
570     if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
571       uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
572       // They have to fit in the 32-bit signed displacement field though.
573       if (isInt<32>(Disp)) {
574         AM.Disp = (uint32_t)Disp;
575         return X86SelectAddress(U->getOperand(0), AM);
576       }
577     }
578     break;
579   }
580
581   case Instruction::GetElementPtr: {
582     X86AddressMode SavedAM = AM;
583
584     // Pattern-match simple GEPs.
585     uint64_t Disp = (int32_t)AM.Disp;
586     unsigned IndexReg = AM.IndexReg;
587     unsigned Scale = AM.Scale;
588     gep_type_iterator GTI = gep_type_begin(U);
589     // Iterate through the indices, folding what we can. Constants can be
590     // folded, and one dynamic index can be handled, if the scale is supported.
591     for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
592          i != e; ++i, ++GTI) {
593       const Value *Op = *i;
594       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
595         const StructLayout *SL = DL.getStructLayout(STy);
596         Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
597         continue;
598       }
599
600       // A array/variable index is always of the form i*S where S is the
601       // constant scale size.  See if we can push the scale into immediates.
602       uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
603       for (;;) {
604         if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
605           // Constant-offset addressing.
606           Disp += CI->getSExtValue() * S;
607           break;
608         }
609         if (canFoldAddIntoGEP(U, Op)) {
610           // A compatible add with a constant operand. Fold the constant.
611           ConstantInt *CI =
612             cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
613           Disp += CI->getSExtValue() * S;
614           // Iterate on the other operand.
615           Op = cast<AddOperator>(Op)->getOperand(0);
616           continue;
617         }
618         if (IndexReg == 0 &&
619             (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
620             (S == 1 || S == 2 || S == 4 || S == 8)) {
621           // Scaled-index addressing.
622           Scale = S;
623           IndexReg = getRegForGEPIndex(Op).first;
624           if (IndexReg == 0)
625             return false;
626           break;
627         }
628         // Unsupported.
629         goto unsupported_gep;
630       }
631     }
632
633     // Check for displacement overflow.
634     if (!isInt<32>(Disp))
635       break;
636
637     AM.IndexReg = IndexReg;
638     AM.Scale = Scale;
639     AM.Disp = (uint32_t)Disp;
640     GEPs.push_back(V);
641
642     if (const GetElementPtrInst *GEP =
643           dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
644       // Ok, the GEP indices were covered by constant-offset and scaled-index
645       // addressing. Update the address state and move on to examining the base.
646       V = GEP;
647       goto redo_gep;
648     } else if (X86SelectAddress(U->getOperand(0), AM)) {
649       return true;
650     }
651
652     // If we couldn't merge the gep value into this addr mode, revert back to
653     // our address and just match the value instead of completely failing.
654     AM = SavedAM;
655
656     for (SmallVectorImpl<const Value *>::reverse_iterator
657            I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
658       if (handleConstantAddresses(*I, AM))
659         return true;
660
661     return false;
662   unsupported_gep:
663     // Ok, the GEP indices weren't all covered.
664     break;
665   }
666   }
667
668   return handleConstantAddresses(V, AM);
669 }
670
671 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
672 ///
673 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
674   const User *U = nullptr;
675   unsigned Opcode = Instruction::UserOp1;
676   const Instruction *I = dyn_cast<Instruction>(V);
677   // Record if the value is defined in the same basic block.
678   //
679   // This information is crucial to know whether or not folding an
680   // operand is valid.
681   // Indeed, FastISel generates or reuses a virtual register for all
682   // operands of all instructions it selects. Obviously, the definition and
683   // its uses must use the same virtual register otherwise the produced
684   // code is incorrect.
685   // Before instruction selection, FunctionLoweringInfo::set sets the virtual
686   // registers for values that are alive across basic blocks. This ensures
687   // that the values are consistently set between across basic block, even
688   // if different instruction selection mechanisms are used (e.g., a mix of
689   // SDISel and FastISel).
690   // For values local to a basic block, the instruction selection process
691   // generates these virtual registers with whatever method is appropriate
692   // for its needs. In particular, FastISel and SDISel do not share the way
693   // local virtual registers are set.
694   // Therefore, this is impossible (or at least unsafe) to share values
695   // between basic blocks unless they use the same instruction selection
696   // method, which is not guarantee for X86.
697   // Moreover, things like hasOneUse could not be used accurately, if we
698   // allow to reference values across basic blocks whereas they are not
699   // alive across basic blocks initially.
700   bool InMBB = true;
701   if (I) {
702     Opcode = I->getOpcode();
703     U = I;
704     InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
705   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
706     Opcode = C->getOpcode();
707     U = C;
708   }
709
710   switch (Opcode) {
711   default: break;
712   case Instruction::BitCast:
713     // Look past bitcasts if its operand is in the same BB.
714     if (InMBB)
715       return X86SelectCallAddress(U->getOperand(0), AM);
716     break;
717
718   case Instruction::IntToPtr:
719     // Look past no-op inttoptrs if its operand is in the same BB.
720     if (InMBB &&
721         TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
722       return X86SelectCallAddress(U->getOperand(0), AM);
723     break;
724
725   case Instruction::PtrToInt:
726     // Look past no-op ptrtoints if its operand is in the same BB.
727     if (InMBB &&
728         TLI.getValueType(U->getType()) == TLI.getPointerTy())
729       return X86SelectCallAddress(U->getOperand(0), AM);
730     break;
731   }
732
733   // Handle constant address.
734   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
735     // Can't handle alternate code models yet.
736     if (TM.getCodeModel() != CodeModel::Small)
737       return false;
738
739     // RIP-relative addresses can't have additional register operands.
740     if (Subtarget->isPICStyleRIPRel() &&
741         (AM.Base.Reg != 0 || AM.IndexReg != 0))
742       return false;
743
744     // Can't handle DbgLocLImport.
745     if (GV->hasDLLImportStorageClass())
746       return false;
747
748     // Can't handle TLS.
749     if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
750       if (GVar->isThreadLocal())
751         return false;
752
753     // Okay, we've committed to selecting this global. Set up the basic address.
754     AM.GV = GV;
755
756     // No ABI requires an extra load for anything other than DLLImport, which
757     // we rejected above. Return a direct reference to the global.
758     if (Subtarget->isPICStyleRIPRel()) {
759       // Use rip-relative addressing if we can.  Above we verified that the
760       // base and index registers are unused.
761       assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
762       AM.Base.Reg = X86::RIP;
763     } else if (Subtarget->isPICStyleStubPIC()) {
764       AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
765     } else if (Subtarget->isPICStyleGOT()) {
766       AM.GVOpFlags = X86II::MO_GOTOFF;
767     }
768
769     return true;
770   }
771
772   // If all else fails, try to materialize the value in a register.
773   if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
774     if (AM.Base.Reg == 0) {
775       AM.Base.Reg = getRegForValue(V);
776       return AM.Base.Reg != 0;
777     }
778     if (AM.IndexReg == 0) {
779       assert(AM.Scale == 1 && "Scale with no index!");
780       AM.IndexReg = getRegForValue(V);
781       return AM.IndexReg != 0;
782     }
783   }
784
785   return false;
786 }
787
788
789 /// X86SelectStore - Select and emit code to implement store instructions.
790 bool X86FastISel::X86SelectStore(const Instruction *I) {
791   // Atomic stores need special handling.
792   const StoreInst *S = cast<StoreInst>(I);
793
794   if (S->isAtomic())
795     return false;
796
797   const Value *Val = S->getValueOperand();
798   const Value *Ptr = S->getPointerOperand();
799
800   MVT VT;
801   if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
802     return false;
803
804   unsigned Alignment = S->getAlignment();
805   unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
806   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
807     Alignment = ABIAlignment;
808   bool Aligned = Alignment >= ABIAlignment;
809
810   X86AddressMode AM;
811   if (!X86SelectAddress(Ptr, AM))
812     return false;
813
814   return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
815 }
816
817 /// X86SelectRet - Select and emit code to implement ret instructions.
818 bool X86FastISel::X86SelectRet(const Instruction *I) {
819   const ReturnInst *Ret = cast<ReturnInst>(I);
820   const Function &F = *I->getParent()->getParent();
821   const X86MachineFunctionInfo *X86MFInfo =
822       FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
823
824   if (!FuncInfo.CanLowerReturn)
825     return false;
826
827   CallingConv::ID CC = F.getCallingConv();
828   if (CC != CallingConv::C &&
829       CC != CallingConv::Fast &&
830       CC != CallingConv::X86_FastCall &&
831       CC != CallingConv::X86_64_SysV)
832     return false;
833
834   if (Subtarget->isCallingConvWin64(CC))
835     return false;
836
837   // Don't handle popping bytes on return for now.
838   if (X86MFInfo->getBytesToPopOnReturn() != 0)
839     return false;
840
841   // fastcc with -tailcallopt is intended to provide a guaranteed
842   // tail call optimization. Fastisel doesn't know how to do that.
843   if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
844     return false;
845
846   // Let SDISel handle vararg functions.
847   if (F.isVarArg())
848     return false;
849
850   // Build a list of return value registers.
851   SmallVector<unsigned, 4> RetRegs;
852
853   if (Ret->getNumOperands() > 0) {
854     SmallVector<ISD::OutputArg, 4> Outs;
855     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
856
857     // Analyze operands of the call, assigning locations to each operand.
858     SmallVector<CCValAssign, 16> ValLocs;
859     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
860                    I->getContext());
861     CCInfo.AnalyzeReturn(Outs, RetCC_X86);
862
863     const Value *RV = Ret->getOperand(0);
864     unsigned Reg = getRegForValue(RV);
865     if (Reg == 0)
866       return false;
867
868     // Only handle a single return value for now.
869     if (ValLocs.size() != 1)
870       return false;
871
872     CCValAssign &VA = ValLocs[0];
873
874     // Don't bother handling odd stuff for now.
875     if (VA.getLocInfo() != CCValAssign::Full)
876       return false;
877     // Only handle register returns for now.
878     if (!VA.isRegLoc())
879       return false;
880
881     // The calling-convention tables for x87 returns don't tell
882     // the whole story.
883     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
884       return false;
885
886     unsigned SrcReg = Reg + VA.getValNo();
887     EVT SrcVT = TLI.getValueType(RV->getType());
888     EVT DstVT = VA.getValVT();
889     // Special handling for extended integers.
890     if (SrcVT != DstVT) {
891       if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
892         return false;
893
894       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
895         return false;
896
897       assert(DstVT == MVT::i32 && "X86 should always ext to i32");
898
899       if (SrcVT == MVT::i1) {
900         if (Outs[0].Flags.isSExt())
901           return false;
902         SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
903         SrcVT = MVT::i8;
904       }
905       unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
906                                              ISD::SIGN_EXTEND;
907       SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
908                           SrcReg, /*TODO: Kill=*/false);
909     }
910
911     // Make the copy.
912     unsigned DstReg = VA.getLocReg();
913     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
914     // Avoid a cross-class copy. This is very unlikely.
915     if (!SrcRC->contains(DstReg))
916       return false;
917     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
918             DstReg).addReg(SrcReg);
919
920     // Add register to return instruction.
921     RetRegs.push_back(VA.getLocReg());
922   }
923
924   // The x86-64 ABI for returning structs by value requires that we copy
925   // the sret argument into %rax for the return. We saved the argument into
926   // a virtual register in the entry block, so now we copy the value out
927   // and into %rax. We also do the same with %eax for Win32.
928   if (F.hasStructRetAttr() &&
929       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
930     unsigned Reg = X86MFInfo->getSRetReturnReg();
931     assert(Reg &&
932            "SRetReturnReg should have been set in LowerFormalArguments()!");
933     unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
934     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
935             RetReg).addReg(Reg);
936     RetRegs.push_back(RetReg);
937   }
938
939   // Now emit the RET.
940   MachineInstrBuilder MIB =
941     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
942   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
943     MIB.addReg(RetRegs[i], RegState::Implicit);
944   return true;
945 }
946
947 /// X86SelectLoad - Select and emit code to implement load instructions.
948 ///
949 bool X86FastISel::X86SelectLoad(const Instruction *I) {
950   const LoadInst *LI = cast<LoadInst>(I);
951
952   // Atomic loads need special handling.
953   if (LI->isAtomic())
954     return false;
955
956   MVT VT;
957   if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
958     return false;
959
960   const Value *Ptr = LI->getPointerOperand();
961
962   X86AddressMode AM;
963   if (!X86SelectAddress(Ptr, AM))
964     return false;
965
966   unsigned ResultReg = 0;
967   if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
968     return false;
969
970   UpdateValueMap(I, ResultReg);
971   return true;
972 }
973
974 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
975   bool HasAVX = Subtarget->hasAVX();
976   bool X86ScalarSSEf32 = Subtarget->hasSSE1();
977   bool X86ScalarSSEf64 = Subtarget->hasSSE2();
978
979   switch (VT.getSimpleVT().SimpleTy) {
980   default:       return 0;
981   case MVT::i8:  return X86::CMP8rr;
982   case MVT::i16: return X86::CMP16rr;
983   case MVT::i32: return X86::CMP32rr;
984   case MVT::i64: return X86::CMP64rr;
985   case MVT::f32:
986     return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
987   case MVT::f64:
988     return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
989   }
990 }
991
992 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
993 /// of the comparison, return an opcode that works for the compare (e.g.
994 /// CMP32ri) otherwise return 0.
995 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
996   switch (VT.getSimpleVT().SimpleTy) {
997   // Otherwise, we can't fold the immediate into this comparison.
998   default: return 0;
999   case MVT::i8: return X86::CMP8ri;
1000   case MVT::i16: return X86::CMP16ri;
1001   case MVT::i32: return X86::CMP32ri;
1002   case MVT::i64:
1003     // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1004     // field.
1005     if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1006       return X86::CMP64ri32;
1007     return 0;
1008   }
1009 }
1010
1011 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1012                                      EVT VT) {
1013   unsigned Op0Reg = getRegForValue(Op0);
1014   if (Op0Reg == 0) return false;
1015
1016   // Handle 'null' like i32/i64 0.
1017   if (isa<ConstantPointerNull>(Op1))
1018     Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1019
1020   // We have two options: compare with register or immediate.  If the RHS of
1021   // the compare is an immediate that we can fold into this compare, use
1022   // CMPri, otherwise use CMPrr.
1023   if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1024     if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1025       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
1026         .addReg(Op0Reg)
1027         .addImm(Op1C->getSExtValue());
1028       return true;
1029     }
1030   }
1031
1032   unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1033   if (CompareOpc == 0) return false;
1034
1035   unsigned Op1Reg = getRegForValue(Op1);
1036   if (Op1Reg == 0) return false;
1037   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
1038     .addReg(Op0Reg)
1039     .addReg(Op1Reg);
1040
1041   return true;
1042 }
1043
1044 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1045   const CmpInst *CI = cast<CmpInst>(I);
1046
1047   MVT VT;
1048   if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1049     return false;
1050
1051   // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1052   static unsigned SETFOpcTable[2][2] = {
1053     { X86::SETEr,  X86::SETNPr },
1054     { X86::SETNEr, X86::SETPr  }
1055   };
1056   unsigned *SETFOpc = nullptr;
1057   switch (CI->getPredicate()) {
1058   default: break;
1059   case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1060   case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1061   }
1062
1063   unsigned ResultReg = createResultReg(&X86::GR8RegClass);
1064   if (SETFOpc) {
1065     if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
1066       return false;
1067
1068     unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1069     unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1070     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1071             FlagReg1);
1072     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1073             FlagReg2);
1074     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::AND8rr),
1075             ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1076     UpdateValueMap(I, ResultReg);
1077     return true;
1078   }
1079
1080   X86::CondCode CC;
1081   bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
1082   std::tie(CC, SwapArgs) = getX86ConditonCode(CI->getPredicate());
1083   assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1084   unsigned Opc = X86::getSETFromCond(CC);
1085
1086   const Value *LHS = CI->getOperand(0);
1087   const Value *RHS = CI->getOperand(1);
1088   if (SwapArgs)
1089     std::swap(LHS, RHS);
1090
1091   // Emit a compare of Op0/Op1.
1092   if (!X86FastEmitCompare(LHS, RHS, VT))
1093     return false;
1094
1095   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1096   UpdateValueMap(I, ResultReg);
1097   return true;
1098 }
1099
1100 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1101   EVT DstVT = TLI.getValueType(I->getType());
1102   if (!TLI.isTypeLegal(DstVT))
1103     return false;
1104
1105   unsigned ResultReg = getRegForValue(I->getOperand(0));
1106   if (ResultReg == 0)
1107     return false;
1108
1109   // Handle zero-extension from i1 to i8, which is common.
1110   MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1111   if (SrcVT.SimpleTy == MVT::i1) {
1112     // Set the high bits to zero.
1113     ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1114     SrcVT = MVT::i8;
1115
1116     if (ResultReg == 0)
1117       return false;
1118   }
1119
1120   if (DstVT == MVT::i64) {
1121     // Handle extension to 64-bits via sub-register shenanigans.
1122     unsigned MovInst;
1123
1124     switch (SrcVT.SimpleTy) {
1125     case MVT::i8:  MovInst = X86::MOVZX32rr8;  break;
1126     case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1127     case MVT::i32: MovInst = X86::MOV32rr;     break;
1128     default: llvm_unreachable("Unexpected zext to i64 source type");
1129     }
1130
1131     unsigned Result32 = createResultReg(&X86::GR32RegClass);
1132     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1133       .addReg(ResultReg);
1134
1135     ResultReg = createResultReg(&X86::GR64RegClass);
1136     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1137             ResultReg)
1138       .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1139   } else if (DstVT != MVT::i8) {
1140     ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1141                            ResultReg, /*Kill=*/true);
1142     if (ResultReg == 0)
1143       return false;
1144   }
1145
1146   UpdateValueMap(I, ResultReg);
1147   return true;
1148 }
1149
1150
1151 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1152   // Unconditional branches are selected by tablegen-generated code.
1153   // Handle a conditional branch.
1154   const BranchInst *BI = cast<BranchInst>(I);
1155   MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1156   MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1157
1158   // Fold the common case of a conditional branch with a comparison
1159   // in the same block (values defined on other blocks may not have
1160   // initialized registers).
1161   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1162     if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1163       EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1164
1165       // Try to take advantage of fallthrough opportunities.
1166       CmpInst::Predicate Predicate = CI->getPredicate();
1167       if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1168         std::swap(TrueMBB, FalseMBB);
1169         Predicate = CmpInst::getInversePredicate(Predicate);
1170       }
1171
1172       // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/conditon
1173       // code check. Instead two branch instructions are required to check all
1174       // the flags. First we change the predicate to a supported conditon code,
1175       // which will be the first branch. Later one we will emit the second
1176       // branch.
1177       bool NeedExtraBranch = false;
1178       switch (Predicate) {
1179       default: break;
1180       case CmpInst::FCMP_OEQ:
1181         std::swap(TrueMBB, FalseMBB); // fall-through
1182       case CmpInst::FCMP_UNE:
1183         NeedExtraBranch = true;
1184         Predicate = CmpInst::FCMP_ONE;
1185         break;
1186       }
1187
1188       X86::CondCode CC;
1189       bool SwapArgs;  // false -> compare Op0, Op1.  true -> compare Op1, Op0.
1190       unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1191       std::tie(CC, SwapArgs) = getX86ConditonCode(Predicate);
1192       assert(CC <= X86::LAST_VALID_COND && "Unexpected conditon code.");
1193
1194       BranchOpc = X86::GetCondBranchFromCond(CC);
1195       const Value *CmpLHS = CI->getOperand(0);
1196       const Value *CmpRHS = CI->getOperand(1);
1197       if (SwapArgs)
1198         std::swap(CmpLHS, CmpRHS);
1199
1200       // Emit a compare of the LHS and RHS, setting the flags.
1201       if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT))
1202         return false;
1203
1204       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1205         .addMBB(TrueMBB);
1206
1207       // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1208       // to UNE above).
1209       if (NeedExtraBranch) {
1210         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1211           .addMBB(TrueMBB);
1212       }
1213
1214       // Obtain the branch weight and add the TrueBB to the successor list.
1215       uint32_t BranchWeight = 0;
1216       if (FuncInfo.BPI)
1217         BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1218                                                    TrueMBB->getBasicBlock());
1219       FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1220
1221       // Emits an unconditional branch to the FalseBB, obtains the branch
1222       // weight, andd adds it to the successor list.
1223       FastEmitBranch(FalseMBB, DbgLoc);
1224
1225       return true;
1226     }
1227   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1228     // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1229     // typically happen for _Bool and C++ bools.
1230     MVT SourceVT;
1231     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1232         isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1233       unsigned TestOpc = 0;
1234       switch (SourceVT.SimpleTy) {
1235       default: break;
1236       case MVT::i8:  TestOpc = X86::TEST8ri; break;
1237       case MVT::i16: TestOpc = X86::TEST16ri; break;
1238       case MVT::i32: TestOpc = X86::TEST32ri; break;
1239       case MVT::i64: TestOpc = X86::TEST64ri32; break;
1240       }
1241       if (TestOpc) {
1242         unsigned OpReg = getRegForValue(TI->getOperand(0));
1243         if (OpReg == 0) return false;
1244         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1245           .addReg(OpReg).addImm(1);
1246
1247         unsigned JmpOpc = X86::JNE_4;
1248         if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1249           std::swap(TrueMBB, FalseMBB);
1250           JmpOpc = X86::JE_4;
1251         }
1252
1253         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1254           .addMBB(TrueMBB);
1255         FastEmitBranch(FalseMBB, DbgLoc);
1256         uint32_t BranchWeight = 0;
1257         if (FuncInfo.BPI)
1258           BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1259                                                      TrueMBB->getBasicBlock());
1260         FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1261         return true;
1262       }
1263     }
1264   }
1265
1266   // Otherwise do a clumsy setcc and re-test it.
1267   // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1268   // in an explicit cast, so make sure to handle that correctly.
1269   unsigned OpReg = getRegForValue(BI->getCondition());
1270   if (OpReg == 0) return false;
1271
1272   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1273     .addReg(OpReg).addImm(1);
1274   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1275     .addMBB(TrueMBB);
1276   FastEmitBranch(FalseMBB, DbgLoc);
1277   uint32_t BranchWeight = 0;
1278   if (FuncInfo.BPI)
1279     BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1280                                                TrueMBB->getBasicBlock());
1281   FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1282   return true;
1283 }
1284
1285 bool X86FastISel::X86SelectShift(const Instruction *I) {
1286   unsigned CReg = 0, OpReg = 0;
1287   const TargetRegisterClass *RC = nullptr;
1288   if (I->getType()->isIntegerTy(8)) {
1289     CReg = X86::CL;
1290     RC = &X86::GR8RegClass;
1291     switch (I->getOpcode()) {
1292     case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1293     case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1294     case Instruction::Shl:  OpReg = X86::SHL8rCL; break;
1295     default: return false;
1296     }
1297   } else if (I->getType()->isIntegerTy(16)) {
1298     CReg = X86::CX;
1299     RC = &X86::GR16RegClass;
1300     switch (I->getOpcode()) {
1301     case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1302     case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1303     case Instruction::Shl:  OpReg = X86::SHL16rCL; break;
1304     default: return false;
1305     }
1306   } else if (I->getType()->isIntegerTy(32)) {
1307     CReg = X86::ECX;
1308     RC = &X86::GR32RegClass;
1309     switch (I->getOpcode()) {
1310     case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1311     case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1312     case Instruction::Shl:  OpReg = X86::SHL32rCL; break;
1313     default: return false;
1314     }
1315   } else if (I->getType()->isIntegerTy(64)) {
1316     CReg = X86::RCX;
1317     RC = &X86::GR64RegClass;
1318     switch (I->getOpcode()) {
1319     case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1320     case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1321     case Instruction::Shl:  OpReg = X86::SHL64rCL; break;
1322     default: return false;
1323     }
1324   } else {
1325     return false;
1326   }
1327
1328   MVT VT;
1329   if (!isTypeLegal(I->getType(), VT))
1330     return false;
1331
1332   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1333   if (Op0Reg == 0) return false;
1334
1335   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1336   if (Op1Reg == 0) return false;
1337   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1338           CReg).addReg(Op1Reg);
1339
1340   // The shift instruction uses X86::CL. If we defined a super-register
1341   // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1342   if (CReg != X86::CL)
1343     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1344             TII.get(TargetOpcode::KILL), X86::CL)
1345       .addReg(CReg, RegState::Kill);
1346
1347   unsigned ResultReg = createResultReg(RC);
1348   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1349     .addReg(Op0Reg);
1350   UpdateValueMap(I, ResultReg);
1351   return true;
1352 }
1353
1354 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1355   const static unsigned NumTypes = 4; // i8, i16, i32, i64
1356   const static unsigned NumOps   = 4; // SDiv, SRem, UDiv, URem
1357   const static bool S = true;  // IsSigned
1358   const static bool U = false; // !IsSigned
1359   const static unsigned Copy = TargetOpcode::COPY;
1360   // For the X86 DIV/IDIV instruction, in most cases the dividend
1361   // (numerator) must be in a specific register pair highreg:lowreg,
1362   // producing the quotient in lowreg and the remainder in highreg.
1363   // For most data types, to set up the instruction, the dividend is
1364   // copied into lowreg, and lowreg is sign-extended or zero-extended
1365   // into highreg.  The exception is i8, where the dividend is defined
1366   // as a single register rather than a register pair, and we
1367   // therefore directly sign-extend or zero-extend the dividend into
1368   // lowreg, instead of copying, and ignore the highreg.
1369   const static struct DivRemEntry {
1370     // The following portion depends only on the data type.
1371     const TargetRegisterClass *RC;
1372     unsigned LowInReg;  // low part of the register pair
1373     unsigned HighInReg; // high part of the register pair
1374     // The following portion depends on both the data type and the operation.
1375     struct DivRemResult {
1376     unsigned OpDivRem;        // The specific DIV/IDIV opcode to use.
1377     unsigned OpSignExtend;    // Opcode for sign-extending lowreg into
1378                               // highreg, or copying a zero into highreg.
1379     unsigned OpCopy;          // Opcode for copying dividend into lowreg, or
1380                               // zero/sign-extending into lowreg for i8.
1381     unsigned DivRemResultReg; // Register containing the desired result.
1382     bool IsOpSigned;          // Whether to use signed or unsigned form.
1383     } ResultTable[NumOps];
1384   } OpTable[NumTypes] = {
1385     { &X86::GR8RegClass,  X86::AX,  0, {
1386         { X86::IDIV8r,  0,            X86::MOVSX16rr8, X86::AL,  S }, // SDiv
1387         { X86::IDIV8r,  0,            X86::MOVSX16rr8, X86::AH,  S }, // SRem
1388         { X86::DIV8r,   0,            X86::MOVZX16rr8, X86::AL,  U }, // UDiv
1389         { X86::DIV8r,   0,            X86::MOVZX16rr8, X86::AH,  U }, // URem
1390       }
1391     }, // i8
1392     { &X86::GR16RegClass, X86::AX,  X86::DX, {
1393         { X86::IDIV16r, X86::CWD,     Copy,            X86::AX,  S }, // SDiv
1394         { X86::IDIV16r, X86::CWD,     Copy,            X86::DX,  S }, // SRem
1395         { X86::DIV16r,  X86::MOV32r0, Copy,            X86::AX,  U }, // UDiv
1396         { X86::DIV16r,  X86::MOV32r0, Copy,            X86::DX,  U }, // URem
1397       }
1398     }, // i16
1399     { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1400         { X86::IDIV32r, X86::CDQ,     Copy,            X86::EAX, S }, // SDiv
1401         { X86::IDIV32r, X86::CDQ,     Copy,            X86::EDX, S }, // SRem
1402         { X86::DIV32r,  X86::MOV32r0, Copy,            X86::EAX, U }, // UDiv
1403         { X86::DIV32r,  X86::MOV32r0, Copy,            X86::EDX, U }, // URem
1404       }
1405     }, // i32
1406     { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1407         { X86::IDIV64r, X86::CQO,     Copy,            X86::RAX, S }, // SDiv
1408         { X86::IDIV64r, X86::CQO,     Copy,            X86::RDX, S }, // SRem
1409         { X86::DIV64r,  X86::MOV32r0, Copy,            X86::RAX, U }, // UDiv
1410         { X86::DIV64r,  X86::MOV32r0, Copy,            X86::RDX, U }, // URem
1411       }
1412     }, // i64
1413   };
1414
1415   MVT VT;
1416   if (!isTypeLegal(I->getType(), VT))
1417     return false;
1418
1419   unsigned TypeIndex, OpIndex;
1420   switch (VT.SimpleTy) {
1421   default: return false;
1422   case MVT::i8:  TypeIndex = 0; break;
1423   case MVT::i16: TypeIndex = 1; break;
1424   case MVT::i32: TypeIndex = 2; break;
1425   case MVT::i64: TypeIndex = 3;
1426     if (!Subtarget->is64Bit())
1427       return false;
1428     break;
1429   }
1430
1431   switch (I->getOpcode()) {
1432   default: llvm_unreachable("Unexpected div/rem opcode");
1433   case Instruction::SDiv: OpIndex = 0; break;
1434   case Instruction::SRem: OpIndex = 1; break;
1435   case Instruction::UDiv: OpIndex = 2; break;
1436   case Instruction::URem: OpIndex = 3; break;
1437   }
1438
1439   const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1440   const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1441   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1442   if (Op0Reg == 0)
1443     return false;
1444   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1445   if (Op1Reg == 0)
1446     return false;
1447
1448   // Move op0 into low-order input register.
1449   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1450           TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1451   // Zero-extend or sign-extend into high-order input register.
1452   if (OpEntry.OpSignExtend) {
1453     if (OpEntry.IsOpSigned)
1454       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1455               TII.get(OpEntry.OpSignExtend));
1456     else {
1457       unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1458       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1459               TII.get(X86::MOV32r0), Zero32);
1460
1461       // Copy the zero into the appropriate sub/super/identical physical
1462       // register. Unfortunately the operations needed are not uniform enough to
1463       // fit neatly into the table above.
1464       if (VT.SimpleTy == MVT::i16) {
1465         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1466                 TII.get(Copy), TypeEntry.HighInReg)
1467           .addReg(Zero32, 0, X86::sub_16bit);
1468       } else if (VT.SimpleTy == MVT::i32) {
1469         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1470                 TII.get(Copy), TypeEntry.HighInReg)
1471             .addReg(Zero32);
1472       } else if (VT.SimpleTy == MVT::i64) {
1473         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1474                 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1475             .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1476       }
1477     }
1478   }
1479   // Generate the DIV/IDIV instruction.
1480   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1481           TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1482   // For i8 remainder, we can't reference AH directly, as we'll end
1483   // up with bogus copies like %R9B = COPY %AH. Reference AX
1484   // instead to prevent AH references in a REX instruction.
1485   //
1486   // The current assumption of the fast register allocator is that isel
1487   // won't generate explicit references to the GPR8_NOREX registers. If
1488   // the allocator and/or the backend get enhanced to be more robust in
1489   // that regard, this can be, and should be, removed.
1490   unsigned ResultReg = 0;
1491   if ((I->getOpcode() == Instruction::SRem ||
1492        I->getOpcode() == Instruction::URem) &&
1493       OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1494     unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1495     unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1496     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1497             TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1498
1499     // Shift AX right by 8 bits instead of using AH.
1500     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1501             ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1502
1503     // Now reference the 8-bit subreg of the result.
1504     ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1505                                            /*Kill=*/true, X86::sub_8bit);
1506   }
1507   // Copy the result out of the physreg if we haven't already.
1508   if (!ResultReg) {
1509     ResultReg = createResultReg(TypeEntry.RC);
1510     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1511         .addReg(OpEntry.DivRemResultReg);
1512   }
1513   UpdateValueMap(I, ResultReg);
1514
1515   return true;
1516 }
1517
1518 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1519   MVT VT;
1520   if (!isTypeLegal(I->getType(), VT))
1521     return false;
1522
1523   // We only use cmov here, if we don't have a cmov instruction bail.
1524   if (!Subtarget->hasCMov()) return false;
1525
1526   unsigned Opc = 0;
1527   const TargetRegisterClass *RC = nullptr;
1528   if (VT == MVT::i16) {
1529     Opc = X86::CMOVE16rr;
1530     RC = &X86::GR16RegClass;
1531   } else if (VT == MVT::i32) {
1532     Opc = X86::CMOVE32rr;
1533     RC = &X86::GR32RegClass;
1534   } else if (VT == MVT::i64) {
1535     Opc = X86::CMOVE64rr;
1536     RC = &X86::GR64RegClass;
1537   } else {
1538     return false;
1539   }
1540
1541   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1542   if (Op0Reg == 0) return false;
1543   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1544   if (Op1Reg == 0) return false;
1545   unsigned Op2Reg = getRegForValue(I->getOperand(2));
1546   if (Op2Reg == 0) return false;
1547
1548   // Selects operate on i1, however, Op0Reg is 8 bits width and may contain
1549   // garbage. Indeed, only the less significant bit is supposed to be accurate.
1550   // If we read more than the lsb, we may see non-zero values whereas lsb
1551   // is zero. Therefore, we have to truncate Op0Reg to i1 for the select.
1552   // This is achieved by performing TEST against 1.
1553   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1554     .addReg(Op0Reg).addImm(1);
1555   unsigned ResultReg = createResultReg(RC);
1556   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1557     .addReg(Op1Reg).addReg(Op2Reg);
1558   UpdateValueMap(I, ResultReg);
1559   return true;
1560 }
1561
1562 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1563   // fpext from float to double.
1564   if (X86ScalarSSEf64 &&
1565       I->getType()->isDoubleTy()) {
1566     const Value *V = I->getOperand(0);
1567     if (V->getType()->isFloatTy()) {
1568       unsigned OpReg = getRegForValue(V);
1569       if (OpReg == 0) return false;
1570       unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1571       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1572               TII.get(X86::CVTSS2SDrr), ResultReg)
1573         .addReg(OpReg);
1574       UpdateValueMap(I, ResultReg);
1575       return true;
1576     }
1577   }
1578
1579   return false;
1580 }
1581
1582 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1583   if (X86ScalarSSEf64) {
1584     if (I->getType()->isFloatTy()) {
1585       const Value *V = I->getOperand(0);
1586       if (V->getType()->isDoubleTy()) {
1587         unsigned OpReg = getRegForValue(V);
1588         if (OpReg == 0) return false;
1589         unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1590         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1591                 TII.get(X86::CVTSD2SSrr), ResultReg)
1592           .addReg(OpReg);
1593         UpdateValueMap(I, ResultReg);
1594         return true;
1595       }
1596     }
1597   }
1598
1599   return false;
1600 }
1601
1602 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1603   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1604   EVT DstVT = TLI.getValueType(I->getType());
1605
1606   // This code only handles truncation to byte.
1607   if (DstVT != MVT::i8 && DstVT != MVT::i1)
1608     return false;
1609   if (!TLI.isTypeLegal(SrcVT))
1610     return false;
1611
1612   unsigned InputReg = getRegForValue(I->getOperand(0));
1613   if (!InputReg)
1614     // Unhandled operand.  Halt "fast" selection and bail.
1615     return false;
1616
1617   if (SrcVT == MVT::i8) {
1618     // Truncate from i8 to i1; no code needed.
1619     UpdateValueMap(I, InputReg);
1620     return true;
1621   }
1622
1623   if (!Subtarget->is64Bit()) {
1624     // If we're on x86-32; we can't extract an i8 from a general register.
1625     // First issue a copy to GR16_ABCD or GR32_ABCD.
1626     const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1627       (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1628       (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1629     unsigned CopyReg = createResultReg(CopyRC);
1630     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1631             CopyReg).addReg(InputReg);
1632     InputReg = CopyReg;
1633   }
1634
1635   // Issue an extract_subreg.
1636   unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1637                                                   InputReg, /*Kill=*/true,
1638                                                   X86::sub_8bit);
1639   if (!ResultReg)
1640     return false;
1641
1642   UpdateValueMap(I, ResultReg);
1643   return true;
1644 }
1645
1646 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1647   return Len <= (Subtarget->is64Bit() ? 32 : 16);
1648 }
1649
1650 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1651                                      X86AddressMode SrcAM, uint64_t Len) {
1652
1653   // Make sure we don't bloat code by inlining very large memcpy's.
1654   if (!IsMemcpySmall(Len))
1655     return false;
1656
1657   bool i64Legal = Subtarget->is64Bit();
1658
1659   // We don't care about alignment here since we just emit integer accesses.
1660   while (Len) {
1661     MVT VT;
1662     if (Len >= 8 && i64Legal)
1663       VT = MVT::i64;
1664     else if (Len >= 4)
1665       VT = MVT::i32;
1666     else if (Len >= 2)
1667       VT = MVT::i16;
1668     else {
1669       VT = MVT::i8;
1670     }
1671
1672     unsigned Reg;
1673     bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
1674     RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
1675     assert(RV && "Failed to emit load or store??");
1676
1677     unsigned Size = VT.getSizeInBits()/8;
1678     Len -= Size;
1679     DestAM.Disp += Size;
1680     SrcAM.Disp += Size;
1681   }
1682
1683   return true;
1684 }
1685
1686 static bool isCommutativeIntrinsic(IntrinsicInst const &I) {
1687   switch (I.getIntrinsicID()) {
1688   case Intrinsic::sadd_with_overflow:
1689   case Intrinsic::uadd_with_overflow:
1690   case Intrinsic::smul_with_overflow:
1691   case Intrinsic::umul_with_overflow:
1692     return true;
1693   default:
1694     return false;
1695   }
1696 }
1697
1698 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1699   // FIXME: Handle more intrinsics.
1700   switch (I.getIntrinsicID()) {
1701   default: return false;
1702   case Intrinsic::frameaddress: {
1703     Type *RetTy = I.getCalledFunction()->getReturnType();
1704
1705     MVT VT;
1706     if (!isTypeLegal(RetTy, VT))
1707       return false;
1708
1709     unsigned Opc;
1710     const TargetRegisterClass *RC = nullptr;
1711
1712     switch (VT.SimpleTy) {
1713     default: llvm_unreachable("Invalid result type for frameaddress.");
1714     case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
1715     case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
1716     }
1717
1718     // This needs to be set before we call getFrameRegister, otherwise we get
1719     // the wrong frame register.
1720     MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
1721     MFI->setFrameAddressIsTaken(true);
1722
1723     const X86RegisterInfo *RegInfo =
1724       static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
1725     unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF));
1726     assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
1727             (FrameReg == X86::EBP && VT == MVT::i32)) &&
1728            "Invalid Frame Register!");
1729
1730     // Always make a copy of the frame register to to a vreg first, so that we
1731     // never directly reference the frame register (the TwoAddressInstruction-
1732     // Pass doesn't like that).
1733     unsigned SrcReg = createResultReg(RC);
1734     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1735             TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
1736
1737     // Now recursively load from the frame address.
1738     // movq (%rbp), %rax
1739     // movq (%rax), %rax
1740     // movq (%rax), %rax
1741     // ...
1742     unsigned DestReg;
1743     unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
1744     while (Depth--) {
1745       DestReg = createResultReg(RC);
1746       addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1747                            TII.get(Opc), DestReg), SrcReg);
1748       SrcReg = DestReg;
1749     }
1750
1751     UpdateValueMap(&I, SrcReg);
1752     return true;
1753   }
1754   case Intrinsic::memcpy: {
1755     const MemCpyInst &MCI = cast<MemCpyInst>(I);
1756     // Don't handle volatile or variable length memcpys.
1757     if (MCI.isVolatile())
1758       return false;
1759
1760     if (isa<ConstantInt>(MCI.getLength())) {
1761       // Small memcpy's are common enough that we want to do them
1762       // without a call if possible.
1763       uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1764       if (IsMemcpySmall(Len)) {
1765         X86AddressMode DestAM, SrcAM;
1766         if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1767             !X86SelectAddress(MCI.getRawSource(), SrcAM))
1768           return false;
1769         TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1770         return true;
1771       }
1772     }
1773
1774     unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1775     if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1776       return false;
1777
1778     if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1779       return false;
1780
1781     return DoSelectCall(&I, "memcpy");
1782   }
1783   case Intrinsic::memset: {
1784     const MemSetInst &MSI = cast<MemSetInst>(I);
1785
1786     if (MSI.isVolatile())
1787       return false;
1788
1789     unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1790     if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1791       return false;
1792
1793     if (MSI.getDestAddressSpace() > 255)
1794       return false;
1795
1796     return DoSelectCall(&I, "memset");
1797   }
1798   case Intrinsic::stackprotector: {
1799     // Emit code to store the stack guard onto the stack.
1800     EVT PtrTy = TLI.getPointerTy();
1801
1802     const Value *Op1 = I.getArgOperand(0); // The guard's value.
1803     const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1804
1805     MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
1806
1807     // Grab the frame index.
1808     X86AddressMode AM;
1809     if (!X86SelectAddress(Slot, AM)) return false;
1810     if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1811     return true;
1812   }
1813   case Intrinsic::dbg_declare: {
1814     const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1815     X86AddressMode AM;
1816     assert(DI->getAddress() && "Null address should be checked earlier!");
1817     if (!X86SelectAddress(DI->getAddress(), AM))
1818       return false;
1819     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1820     // FIXME may need to add RegState::Debug to any registers produced,
1821     // although ESP/EBP should be the only ones at the moment.
1822     addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
1823       addImm(0).addMetadata(DI->getVariable());
1824     return true;
1825   }
1826   case Intrinsic::trap: {
1827     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
1828     return true;
1829   }
1830   case Intrinsic::sqrt: {
1831     if (!Subtarget->hasSSE1())
1832       return false;
1833
1834     Type *RetTy = I.getCalledFunction()->getReturnType();
1835
1836     MVT VT;
1837     if (!isTypeLegal(RetTy, VT))
1838       return false;
1839
1840     // Unfortunatelly we can't use FastEmit_r, because the AVX version of FSQRT
1841     // is not generated by FastISel yet.
1842     // FIXME: Update this code once tablegen can handle it.
1843     static const unsigned SqrtOpc[2][2] = {
1844       {X86::SQRTSSr, X86::VSQRTSSr},
1845       {X86::SQRTSDr, X86::VSQRTSDr}
1846     };
1847     bool HasAVX = Subtarget->hasAVX();
1848     unsigned Opc;
1849     const TargetRegisterClass *RC;
1850     switch (VT.SimpleTy) {
1851     default: return false;
1852     case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
1853     case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
1854     }
1855
1856     const Value *SrcVal = I.getArgOperand(0);
1857     unsigned SrcReg = getRegForValue(SrcVal);
1858
1859     if (SrcReg == 0)
1860       return false;
1861
1862     unsigned ImplicitDefReg = 0;
1863     if (HasAVX) {
1864       ImplicitDefReg = createResultReg(RC);
1865       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1866               TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
1867     }
1868
1869     unsigned ResultReg = createResultReg(RC);
1870     MachineInstrBuilder MIB;
1871     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1872                   ResultReg);
1873
1874     if (ImplicitDefReg)
1875       MIB.addReg(ImplicitDefReg);
1876
1877     MIB.addReg(SrcReg);
1878
1879     UpdateValueMap(&I, ResultReg);
1880     return true;
1881   }
1882   case Intrinsic::sadd_with_overflow:
1883   case Intrinsic::uadd_with_overflow:
1884   case Intrinsic::ssub_with_overflow:
1885   case Intrinsic::usub_with_overflow:
1886   case Intrinsic::smul_with_overflow:
1887   case Intrinsic::umul_with_overflow: {
1888     // This implements the basic lowering of the xalu with overflow intrinsics
1889     // into add/sub/mul folowed by either seto or setb.
1890     const Function *Callee = I.getCalledFunction();
1891     auto *Ty = cast<StructType>(Callee->getReturnType());
1892     Type *RetTy = Ty->getTypeAtIndex(0U);
1893     Type *CondTy = Ty->getTypeAtIndex(1);
1894
1895     MVT VT;
1896     if (!isTypeLegal(RetTy, VT))
1897       return false;
1898
1899     if (VT < MVT::i8 || VT > MVT::i64)
1900       return false;
1901
1902     const Value *LHS = I.getArgOperand(0);
1903     const Value *RHS = I.getArgOperand(1);
1904
1905     // Canonicalize immediates to the RHS.
1906     if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
1907         isCommutativeIntrinsic(I))
1908       std::swap(LHS, RHS);
1909
1910     unsigned BaseOpc, CondOpc;
1911     switch (I.getIntrinsicID()) {
1912     default: llvm_unreachable("Unexpected intrinsic!");
1913     case Intrinsic::sadd_with_overflow:
1914       BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break;
1915     case Intrinsic::uadd_with_overflow:
1916       BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
1917     case Intrinsic::ssub_with_overflow:
1918       BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break;
1919     case Intrinsic::usub_with_overflow:
1920       BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
1921     case Intrinsic::smul_with_overflow:
1922       BaseOpc = ISD::MUL; CondOpc = X86::SETOr; break;
1923     case Intrinsic::umul_with_overflow:
1924       BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
1925     }
1926
1927     unsigned LHSReg = getRegForValue(LHS);
1928     if (LHSReg == 0)
1929       return false;
1930     bool LHSIsKill = hasTrivialKill(LHS);
1931
1932     unsigned ResultReg = 0;
1933     // Check if we have an immediate version.
1934     if (auto const *C = dyn_cast<ConstantInt>(RHS)) {
1935       ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
1936                               C->getZExtValue());
1937     }
1938
1939     unsigned RHSReg;
1940     bool RHSIsKill;
1941     if (!ResultReg) {
1942       RHSReg = getRegForValue(RHS);
1943       if (RHSReg == 0)
1944         return false;
1945       RHSIsKill = hasTrivialKill(RHS);
1946       ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
1947                               RHSIsKill);
1948     }
1949
1950     // FastISel doesn't have a pattern for X86::MUL*r. Emit it manually.
1951     if (BaseOpc == X86ISD::UMUL && !ResultReg) {
1952       static const unsigned MULOpc[] =
1953       { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
1954       static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
1955       // First copy the first operand into RAX, which is an implicit input to
1956       // the X86::MUL*r instruction.
1957       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1958               TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
1959         .addReg(LHSReg, getKillRegState(LHSIsKill));
1960       ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
1961                                  TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
1962     }
1963
1964     if (!ResultReg)
1965       return false;
1966
1967     unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
1968     assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
1969     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
1970             ResultReg2);
1971
1972     UpdateValueMap(&I, ResultReg, 2);
1973     return true;
1974   }
1975   case Intrinsic::x86_sse_cvttss2si:
1976   case Intrinsic::x86_sse_cvttss2si64:
1977   case Intrinsic::x86_sse2_cvttsd2si:
1978   case Intrinsic::x86_sse2_cvttsd2si64: {
1979     bool IsInputDouble;
1980     switch (I.getIntrinsicID()) {
1981     default: llvm_unreachable("Unexpected intrinsic.");
1982     case Intrinsic::x86_sse_cvttss2si:
1983     case Intrinsic::x86_sse_cvttss2si64:
1984       if (!Subtarget->hasSSE1())
1985         return false;
1986       IsInputDouble = false;
1987       break;
1988     case Intrinsic::x86_sse2_cvttsd2si:
1989     case Intrinsic::x86_sse2_cvttsd2si64:
1990       if (!Subtarget->hasSSE2())
1991         return false;
1992       IsInputDouble = true;
1993       break;
1994     }
1995
1996     Type *RetTy = I.getCalledFunction()->getReturnType();
1997     MVT VT;
1998     if (!isTypeLegal(RetTy, VT))
1999       return false;
2000
2001     static const unsigned CvtOpc[2][2][2] = {
2002       { { X86::CVTTSS2SIrr,   X86::VCVTTSS2SIrr   },
2003         { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr }  },
2004       { { X86::CVTTSD2SIrr,   X86::VCVTTSD2SIrr   },
2005         { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr }  }
2006     };
2007     bool HasAVX = Subtarget->hasAVX();
2008     unsigned Opc;
2009     switch (VT.SimpleTy) {
2010     default: llvm_unreachable("Unexpected result type.");
2011     case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2012     case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2013     }
2014
2015     // Check if we can fold insertelement instructions into the convert.
2016     const Value *Op = I.getArgOperand(0);
2017     while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2018       const Value *Index = IE->getOperand(2);
2019       if (!isa<ConstantInt>(Index))
2020         break;
2021       unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2022
2023       if (Idx == 0) {
2024         Op = IE->getOperand(1);
2025         break;
2026       }
2027       Op = IE->getOperand(0);
2028     }
2029
2030     unsigned Reg = getRegForValue(Op);
2031     if (Reg == 0)
2032       return false;
2033
2034     unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2035     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2036       .addReg(Reg);
2037
2038     UpdateValueMap(&I, ResultReg);
2039     return true;
2040   }
2041   }
2042 }
2043
2044 bool X86FastISel::FastLowerArguments() {
2045   if (!FuncInfo.CanLowerReturn)
2046     return false;
2047
2048   const Function *F = FuncInfo.Fn;
2049   if (F->isVarArg())
2050     return false;
2051
2052   CallingConv::ID CC = F->getCallingConv();
2053   if (CC != CallingConv::C)
2054     return false;
2055
2056   if (Subtarget->isCallingConvWin64(CC))
2057     return false;
2058
2059   if (!Subtarget->is64Bit())
2060     return false;
2061   
2062   // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2063   unsigned GPRCnt = 0;
2064   unsigned FPRCnt = 0;
2065   unsigned Idx = 0;
2066   for (auto const &Arg : F->args()) {
2067     // The first argument is at index 1.
2068     ++Idx;
2069     if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2070         F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2071         F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2072         F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2073       return false;
2074
2075     Type *ArgTy = Arg.getType();
2076     if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2077       return false;
2078
2079     EVT ArgVT = TLI.getValueType(ArgTy);
2080     if (!ArgVT.isSimple()) return false;
2081     switch (ArgVT.getSimpleVT().SimpleTy) {
2082     default: return false;
2083     case MVT::i32:
2084     case MVT::i64:
2085       ++GPRCnt;
2086       break;
2087     case MVT::f32:
2088     case MVT::f64:
2089       if (!Subtarget->hasSSE1())
2090         return false;
2091       ++FPRCnt;
2092       break;
2093     }
2094
2095     if (GPRCnt > 6)
2096       return false;
2097
2098     if (FPRCnt > 8)
2099       return false;
2100   }
2101
2102   static const MCPhysReg GPR32ArgRegs[] = {
2103     X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2104   };
2105   static const MCPhysReg GPR64ArgRegs[] = {
2106     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2107   };
2108   static const MCPhysReg XMMArgRegs[] = {
2109     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2110     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2111   };
2112
2113   unsigned GPRIdx = 0;
2114   unsigned FPRIdx = 0;
2115   for (auto const &Arg : F->args()) {
2116     MVT VT = TLI.getSimpleValueType(Arg.getType());
2117     const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2118     unsigned SrcReg;
2119     switch (VT.SimpleTy) {
2120     default: llvm_unreachable("Unexpected value type.");
2121     case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2122     case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2123     case MVT::f32: // fall-through
2124     case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2125     }
2126     unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2127     // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2128     // Without this, EmitLiveInCopies may eliminate the livein if its only
2129     // use is a bitcast (which isn't turned into an instruction).
2130     unsigned ResultReg = createResultReg(RC);
2131     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2132             TII.get(TargetOpcode::COPY), ResultReg)
2133       .addReg(DstReg, getKillRegState(true));
2134     UpdateValueMap(&Arg, ResultReg);
2135   }
2136   return true;
2137 }
2138
2139 bool X86FastISel::X86SelectCall(const Instruction *I) {
2140   const CallInst *CI = cast<CallInst>(I);
2141   const Value *Callee = CI->getCalledValue();
2142
2143   // Can't handle inline asm yet.
2144   if (isa<InlineAsm>(Callee))
2145     return false;
2146
2147   // Handle intrinsic calls.
2148   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
2149     return X86VisitIntrinsicCall(*II);
2150
2151   // Allow SelectionDAG isel to handle tail calls.
2152   if (cast<CallInst>(I)->isTailCall())
2153     return false;
2154
2155   return DoSelectCall(I, nullptr);
2156 }
2157
2158 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
2159                                            const ImmutableCallSite &CS) {
2160   if (Subtarget.is64Bit())
2161     return 0;
2162   if (Subtarget.getTargetTriple().isOSMSVCRT())
2163     return 0;
2164   CallingConv::ID CC = CS.getCallingConv();
2165   if (CC == CallingConv::Fast || CC == CallingConv::GHC)
2166     return 0;
2167   if (!CS.paramHasAttr(1, Attribute::StructRet))
2168     return 0;
2169   if (CS.paramHasAttr(1, Attribute::InReg))
2170     return 0;
2171   return 4;
2172 }
2173
2174 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
2175 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
2176   const CallInst *CI = cast<CallInst>(I);
2177   const Value *Callee = CI->getCalledValue();
2178
2179   // Handle only C and fastcc calling conventions for now.
2180   ImmutableCallSite CS(CI);
2181   CallingConv::ID CC = CS.getCallingConv();
2182   bool isWin64 = Subtarget->isCallingConvWin64(CC);
2183   if (CC != CallingConv::C && CC != CallingConv::Fast &&
2184       CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
2185       CC != CallingConv::X86_64_SysV)
2186     return false;
2187
2188   // fastcc with -tailcallopt is intended to provide a guaranteed
2189   // tail call optimization. Fastisel doesn't know how to do that.
2190   if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2191     return false;
2192
2193   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2194   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2195   bool isVarArg = FTy->isVarArg();
2196
2197   // Don't know how to handle Win64 varargs yet.  Nothing special needed for
2198   // x86-32.  Special handling for x86-64 is implemented.
2199   if (isVarArg && isWin64)
2200     return false;
2201
2202   // Don't know about inalloca yet.
2203   if (CS.hasInAllocaArgument())
2204     return false;
2205
2206   // Fast-isel doesn't know about callee-pop yet.
2207   if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
2208                        TM.Options.GuaranteedTailCallOpt))
2209     return false;
2210
2211   // Check whether the function can return without sret-demotion.
2212   SmallVector<ISD::OutputArg, 4> Outs;
2213   GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
2214   bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
2215                                            *FuncInfo.MF, FTy->isVarArg(),
2216                                            Outs, FTy->getContext());
2217   if (!CanLowerReturn)
2218     return false;
2219
2220   // Materialize callee address in a register. FIXME: GV address can be
2221   // handled with a CALLpcrel32 instead.
2222   X86AddressMode CalleeAM;
2223   if (!X86SelectCallAddress(Callee, CalleeAM))
2224     return false;
2225   unsigned CalleeOp = 0;
2226   const GlobalValue *GV = nullptr;
2227   if (CalleeAM.GV != nullptr) {
2228     GV = CalleeAM.GV;
2229   } else if (CalleeAM.Base.Reg != 0) {
2230     CalleeOp = CalleeAM.Base.Reg;
2231   } else
2232     return false;
2233
2234   // Deal with call operands first.
2235   SmallVector<const Value *, 8> ArgVals;
2236   SmallVector<unsigned, 8> Args;
2237   SmallVector<MVT, 8> ArgVTs;
2238   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2239   unsigned arg_size = CS.arg_size();
2240   Args.reserve(arg_size);
2241   ArgVals.reserve(arg_size);
2242   ArgVTs.reserve(arg_size);
2243   ArgFlags.reserve(arg_size);
2244   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2245        i != e; ++i) {
2246     // If we're lowering a mem intrinsic instead of a regular call, skip the
2247     // last two arguments, which should not passed to the underlying functions.
2248     if (MemIntName && e-i <= 2)
2249       break;
2250     Value *ArgVal = *i;
2251     ISD::ArgFlagsTy Flags;
2252     unsigned AttrInd = i - CS.arg_begin() + 1;
2253     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2254       Flags.setSExt();
2255     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2256       Flags.setZExt();
2257
2258     if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
2259       PointerType *Ty = cast<PointerType>(ArgVal->getType());
2260       Type *ElementTy = Ty->getElementType();
2261       unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
2262       unsigned FrameAlign = CS.getParamAlignment(AttrInd);
2263       if (!FrameAlign)
2264         FrameAlign = TLI.getByValTypeAlignment(ElementTy);
2265       Flags.setByVal();
2266       Flags.setByValSize(FrameSize);
2267       Flags.setByValAlign(FrameAlign);
2268       if (!IsMemcpySmall(FrameSize))
2269         return false;
2270     }
2271
2272     if (CS.paramHasAttr(AttrInd, Attribute::InReg))
2273       Flags.setInReg();
2274     if (CS.paramHasAttr(AttrInd, Attribute::Nest))
2275       Flags.setNest();
2276
2277     // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
2278     // instruction.  This is safe because it is common to all fastisel supported
2279     // calling conventions on x86.
2280     if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
2281       if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
2282           CI->getBitWidth() == 16) {
2283         if (Flags.isSExt())
2284           ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
2285         else
2286           ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2287       }
2288     }
2289
2290     unsigned ArgReg;
2291
2292     // Passing bools around ends up doing a trunc to i1 and passing it.
2293     // Codegen this as an argument + "and 1".
2294     if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2295         cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2296         ArgVal->hasOneUse()) {
2297       ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2298       ArgReg = getRegForValue(ArgVal);
2299       if (ArgReg == 0) return false;
2300
2301       MVT ArgVT;
2302       if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2303
2304       ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2305                            ArgVal->hasOneUse(), 1);
2306     } else {
2307       ArgReg = getRegForValue(ArgVal);
2308     }
2309
2310     if (ArgReg == 0) return false;
2311
2312     Type *ArgTy = ArgVal->getType();
2313     MVT ArgVT;
2314     if (!isTypeLegal(ArgTy, ArgVT))
2315       return false;
2316     if (ArgVT == MVT::x86mmx)
2317       return false;
2318     unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2319     Flags.setOrigAlign(OriginalAlignment);
2320
2321     Args.push_back(ArgReg);
2322     ArgVals.push_back(ArgVal);
2323     ArgVTs.push_back(ArgVT);
2324     ArgFlags.push_back(Flags);
2325   }
2326
2327   // Analyze operands of the call, assigning locations to each operand.
2328   SmallVector<CCValAssign, 16> ArgLocs;
2329   CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2330                  I->getParent()->getContext());
2331
2332   // Allocate shadow area for Win64
2333   if (isWin64)
2334     CCInfo.AllocateStack(32, 8);
2335
2336   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2337
2338   // Get a count of how many bytes are to be pushed on the stack.
2339   unsigned NumBytes = CCInfo.getNextStackOffset();
2340
2341   // Issue CALLSEQ_START
2342   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2343   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2344     .addImm(NumBytes);
2345
2346   // Process argument: walk the register/memloc assignments, inserting
2347   // copies / loads.
2348   SmallVector<unsigned, 4> RegArgs;
2349   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2350     CCValAssign &VA = ArgLocs[i];
2351     unsigned Arg = Args[VA.getValNo()];
2352     EVT ArgVT = ArgVTs[VA.getValNo()];
2353
2354     // Promote the value if needed.
2355     switch (VA.getLocInfo()) {
2356     case CCValAssign::Full: break;
2357     case CCValAssign::SExt: {
2358       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2359              "Unexpected extend");
2360       bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2361                                        Arg, ArgVT, Arg);
2362       assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2363       ArgVT = VA.getLocVT();
2364       break;
2365     }
2366     case CCValAssign::ZExt: {
2367       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2368              "Unexpected extend");
2369       bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2370                                        Arg, ArgVT, Arg);
2371       assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2372       ArgVT = VA.getLocVT();
2373       break;
2374     }
2375     case CCValAssign::AExt: {
2376       assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2377              "Unexpected extend");
2378       bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2379                                        Arg, ArgVT, Arg);
2380       if (!Emitted)
2381         Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2382                                     Arg, ArgVT, Arg);
2383       if (!Emitted)
2384         Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2385                                     Arg, ArgVT, Arg);
2386
2387       assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2388       ArgVT = VA.getLocVT();
2389       break;
2390     }
2391     case CCValAssign::BCvt: {
2392       unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2393                                ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2394       assert(BC != 0 && "Failed to emit a bitcast!");
2395       Arg = BC;
2396       ArgVT = VA.getLocVT();
2397       break;
2398     }
2399     case CCValAssign::VExt: 
2400       // VExt has not been implemented, so this should be impossible to reach
2401       // for now.  However, fallback to Selection DAG isel once implemented.
2402       return false;
2403     case CCValAssign::Indirect:
2404       // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2405       // support this.
2406       return false;
2407     case CCValAssign::FPExt:
2408       llvm_unreachable("Unexpected loc info!");
2409     }
2410
2411     if (VA.isRegLoc()) {
2412       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2413               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2414       RegArgs.push_back(VA.getLocReg());
2415     } else {
2416       unsigned LocMemOffset = VA.getLocMemOffset();
2417       X86AddressMode AM;
2418       const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2419           getTargetMachine()->getRegisterInfo());
2420       AM.Base.Reg = RegInfo->getStackRegister();
2421       AM.Disp = LocMemOffset;
2422       const Value *ArgVal = ArgVals[VA.getValNo()];
2423       ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2424
2425       if (Flags.isByVal()) {
2426         X86AddressMode SrcAM;
2427         SrcAM.Base.Reg = Arg;
2428         bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2429         assert(Res && "memcpy length already checked!"); (void)Res;
2430       } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2431         // If this is a really simple value, emit this with the Value* version
2432         // of X86FastEmitStore.  If it isn't simple, we don't want to do this,
2433         // as it can cause us to reevaluate the argument.
2434         if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2435           return false;
2436       } else {
2437         if (!X86FastEmitStore(ArgVT, Arg, /*ValIsKill=*/false, AM))
2438           return false;
2439       }
2440     }
2441   }
2442
2443   // ELF / PIC requires GOT in the EBX register before function calls via PLT
2444   // GOT pointer.
2445   if (Subtarget->isPICStyleGOT()) {
2446     unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2447     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2448             TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2449   }
2450
2451   if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2452     // Count the number of XMM registers allocated.
2453     static const MCPhysReg XMMArgRegs[] = {
2454       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2455       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2456     };
2457     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2458     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2459             X86::AL).addImm(NumXMMRegs);
2460   }
2461
2462   // Issue the call.
2463   MachineInstrBuilder MIB;
2464   if (CalleeOp) {
2465     // Register-indirect call.
2466     unsigned CallOpc;
2467     if (Subtarget->is64Bit())
2468       CallOpc = X86::CALL64r;
2469     else
2470       CallOpc = X86::CALL32r;
2471     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2472       .addReg(CalleeOp);
2473
2474   } else {
2475     // Direct call.
2476     assert(GV && "Not a direct call");
2477     unsigned CallOpc;
2478     if (Subtarget->is64Bit())
2479       CallOpc = X86::CALL64pcrel32;
2480     else
2481       CallOpc = X86::CALLpcrel32;
2482
2483     // See if we need any target-specific flags on the GV operand.
2484     unsigned char OpFlags = 0;
2485
2486     // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2487     // external symbols most go through the PLT in PIC mode.  If the symbol
2488     // has hidden or protected visibility, or if it is static or local, then
2489     // we don't need to use the PLT - we can directly call it.
2490     if (Subtarget->isTargetELF() &&
2491         TM.getRelocationModel() == Reloc::PIC_ &&
2492         GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2493       OpFlags = X86II::MO_PLT;
2494     } else if (Subtarget->isPICStyleStubAny() &&
2495                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2496                (!Subtarget->getTargetTriple().isMacOSX() ||
2497                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2498       // PC-relative references to external symbols should go through $stub,
2499       // unless we're building with the leopard linker or later, which
2500       // automatically synthesizes these stubs.
2501       OpFlags = X86II::MO_DARWIN_STUB;
2502     }
2503
2504
2505     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2506     if (MemIntName)
2507       MIB.addExternalSymbol(MemIntName, OpFlags);
2508     else
2509       MIB.addGlobalAddress(GV, 0, OpFlags);
2510   }
2511
2512   // Add a register mask with the call-preserved registers.
2513   // Proper defs for return values will be added by setPhysRegsDeadExcept().
2514   MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2515
2516   // Add an implicit use GOT pointer in EBX.
2517   if (Subtarget->isPICStyleGOT())
2518     MIB.addReg(X86::EBX, RegState::Implicit);
2519
2520   if (Subtarget->is64Bit() && isVarArg && !isWin64)
2521     MIB.addReg(X86::AL, RegState::Implicit);
2522
2523   // Add implicit physical register uses to the call.
2524   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2525     MIB.addReg(RegArgs[i], RegState::Implicit);
2526
2527   // Issue CALLSEQ_END
2528   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2529   const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2530   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2531     .addImm(NumBytes).addImm(NumBytesCallee);
2532
2533   // Build info for return calling conv lowering code.
2534   // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2535   SmallVector<ISD::InputArg, 32> Ins;
2536   SmallVector<EVT, 4> RetTys;
2537   ComputeValueVTs(TLI, I->getType(), RetTys);
2538   for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2539     EVT VT = RetTys[i];
2540     MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2541     unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2542     for (unsigned j = 0; j != NumRegs; ++j) {
2543       ISD::InputArg MyFlags;
2544       MyFlags.VT = RegisterVT;
2545       MyFlags.Used = !CS.getInstruction()->use_empty();
2546       if (CS.paramHasAttr(0, Attribute::SExt))
2547         MyFlags.Flags.setSExt();
2548       if (CS.paramHasAttr(0, Attribute::ZExt))
2549         MyFlags.Flags.setZExt();
2550       if (CS.paramHasAttr(0, Attribute::InReg))
2551         MyFlags.Flags.setInReg();
2552       Ins.push_back(MyFlags);
2553     }
2554   }
2555
2556   // Now handle call return values.
2557   SmallVector<unsigned, 4> UsedRegs;
2558   SmallVector<CCValAssign, 16> RVLocs;
2559   CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2560                     I->getParent()->getContext());
2561   unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2562   CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2563   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2564     EVT CopyVT = RVLocs[i].getValVT();
2565     unsigned CopyReg = ResultReg + i;
2566
2567     // If this is a call to a function that returns an fp value on the x87 fp
2568     // stack, but where we prefer to use the value in xmm registers, copy it
2569     // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2570     if ((RVLocs[i].getLocReg() == X86::ST0 ||
2571          RVLocs[i].getLocReg() == X86::ST1)) {
2572       if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2573         CopyVT = MVT::f80;
2574         CopyReg = createResultReg(&X86::RFP80RegClass);
2575       }
2576       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2577               TII.get(X86::FpPOP_RETVAL), CopyReg);
2578     } else {
2579       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2580               TII.get(TargetOpcode::COPY),
2581               CopyReg).addReg(RVLocs[i].getLocReg());
2582       UsedRegs.push_back(RVLocs[i].getLocReg());
2583     }
2584
2585     if (CopyVT != RVLocs[i].getValVT()) {
2586       // Round the F80 the right size, which also moves to the appropriate xmm
2587       // register. This is accomplished by storing the F80 value in memory and
2588       // then loading it back. Ewww...
2589       EVT ResVT = RVLocs[i].getValVT();
2590       unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2591       unsigned MemSize = ResVT.getSizeInBits()/8;
2592       int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2593       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2594                                 TII.get(Opc)), FI)
2595         .addReg(CopyReg);
2596       Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2597       addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2598                                 TII.get(Opc), ResultReg + i), FI);
2599     }
2600   }
2601
2602   if (RVLocs.size())
2603     UpdateValueMap(I, ResultReg, RVLocs.size());
2604
2605   // Set all unused physreg defs as dead.
2606   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2607
2608   return true;
2609 }
2610
2611
2612 bool
2613 X86FastISel::TargetSelectInstruction(const Instruction *I)  {
2614   switch (I->getOpcode()) {
2615   default: break;
2616   case Instruction::Load:
2617     return X86SelectLoad(I);
2618   case Instruction::Store:
2619     return X86SelectStore(I);
2620   case Instruction::Ret:
2621     return X86SelectRet(I);
2622   case Instruction::ICmp:
2623   case Instruction::FCmp:
2624     return X86SelectCmp(I);
2625   case Instruction::ZExt:
2626     return X86SelectZExt(I);
2627   case Instruction::Br:
2628     return X86SelectBranch(I);
2629   case Instruction::Call:
2630     return X86SelectCall(I);
2631   case Instruction::LShr:
2632   case Instruction::AShr:
2633   case Instruction::Shl:
2634     return X86SelectShift(I);
2635   case Instruction::SDiv:
2636   case Instruction::UDiv:
2637   case Instruction::SRem:
2638   case Instruction::URem:
2639     return X86SelectDivRem(I);
2640   case Instruction::Select:
2641     return X86SelectSelect(I);
2642   case Instruction::Trunc:
2643     return X86SelectTrunc(I);
2644   case Instruction::FPExt:
2645     return X86SelectFPExt(I);
2646   case Instruction::FPTrunc:
2647     return X86SelectFPTrunc(I);
2648   case Instruction::IntToPtr: // Deliberate fall-through.
2649   case Instruction::PtrToInt: {
2650     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2651     EVT DstVT = TLI.getValueType(I->getType());
2652     if (DstVT.bitsGT(SrcVT))
2653       return X86SelectZExt(I);
2654     if (DstVT.bitsLT(SrcVT))
2655       return X86SelectTrunc(I);
2656     unsigned Reg = getRegForValue(I->getOperand(0));
2657     if (Reg == 0) return false;
2658     UpdateValueMap(I, Reg);
2659     return true;
2660   }
2661   }
2662
2663   return false;
2664 }
2665
2666 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2667   MVT VT;
2668   if (!isTypeLegal(C->getType(), VT))
2669     return 0;
2670
2671   // Can't handle alternate code models yet.
2672   if (TM.getCodeModel() != CodeModel::Small)
2673     return 0;
2674
2675   // Get opcode and regclass of the output for the given load instruction.
2676   unsigned Opc = 0;
2677   const TargetRegisterClass *RC = nullptr;
2678   switch (VT.SimpleTy) {
2679   default: return 0;
2680   case MVT::i8:
2681     Opc = X86::MOV8rm;
2682     RC  = &X86::GR8RegClass;
2683     break;
2684   case MVT::i16:
2685     Opc = X86::MOV16rm;
2686     RC  = &X86::GR16RegClass;
2687     break;
2688   case MVT::i32:
2689     Opc = X86::MOV32rm;
2690     RC  = &X86::GR32RegClass;
2691     break;
2692   case MVT::i64:
2693     // Must be in x86-64 mode.
2694     Opc = X86::MOV64rm;
2695     RC  = &X86::GR64RegClass;
2696     break;
2697   case MVT::f32:
2698     if (X86ScalarSSEf32) {
2699       Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2700       RC  = &X86::FR32RegClass;
2701     } else {
2702       Opc = X86::LD_Fp32m;
2703       RC  = &X86::RFP32RegClass;
2704     }
2705     break;
2706   case MVT::f64:
2707     if (X86ScalarSSEf64) {
2708       Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2709       RC  = &X86::FR64RegClass;
2710     } else {
2711       Opc = X86::LD_Fp64m;
2712       RC  = &X86::RFP64RegClass;
2713     }
2714     break;
2715   case MVT::f80:
2716     // No f80 support yet.
2717     return 0;
2718   }
2719
2720   // Materialize addresses with LEA instructions.
2721   if (isa<GlobalValue>(C)) {
2722     // LEA can only handle 32 bit immediates. Currently this happens pretty
2723     // rarely, so rather than deal with it just bail out of fast isel. If any
2724     // architectures endis up needing to use this path a lot then fast isel
2725     // could get the address with a MOV64ri and use that to load the value.
2726     if (TM.getRelocationModel() == Reloc::Static && Subtarget->is64Bit())
2727       return false;
2728
2729     X86AddressMode AM;
2730     if (X86SelectAddress(C, AM)) {
2731       // If the expression is just a basereg, then we're done, otherwise we need
2732       // to emit an LEA.
2733       if (AM.BaseType == X86AddressMode::RegBase &&
2734           AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
2735         return AM.Base.Reg;
2736
2737       Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2738       unsigned ResultReg = createResultReg(RC);
2739       addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2740                              TII.get(Opc), ResultReg), AM);
2741       return ResultReg;
2742     }
2743     return 0;
2744   }
2745
2746   // MachineConstantPool wants an explicit alignment.
2747   unsigned Align = DL.getPrefTypeAlignment(C->getType());
2748   if (Align == 0) {
2749     // Alignment of vector types.  FIXME!
2750     Align = DL.getTypeAllocSize(C->getType());
2751   }
2752
2753   // x86-32 PIC requires a PIC base register for constant pools.
2754   unsigned PICBase = 0;
2755   unsigned char OpFlag = 0;
2756   if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2757     OpFlag = X86II::MO_PIC_BASE_OFFSET;
2758     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2759   } else if (Subtarget->isPICStyleGOT()) {
2760     OpFlag = X86II::MO_GOTOFF;
2761     PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2762   } else if (Subtarget->isPICStyleRIPRel() &&
2763              TM.getCodeModel() == CodeModel::Small) {
2764     PICBase = X86::RIP;
2765   }
2766
2767   // Create the load from the constant pool.
2768   unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2769   unsigned ResultReg = createResultReg(RC);
2770   addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2771                                    TII.get(Opc), ResultReg),
2772                            MCPOffset, PICBase, OpFlag);
2773
2774   return ResultReg;
2775 }
2776
2777 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2778   // Fail on dynamic allocas. At this point, getRegForValue has already
2779   // checked its CSE maps, so if we're here trying to handle a dynamic
2780   // alloca, we're not going to succeed. X86SelectAddress has a
2781   // check for dynamic allocas, because it's called directly from
2782   // various places, but TargetMaterializeAlloca also needs a check
2783   // in order to avoid recursion between getRegForValue,
2784   // X86SelectAddrss, and TargetMaterializeAlloca.
2785   if (!FuncInfo.StaticAllocaMap.count(C))
2786     return 0;
2787   assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
2788
2789   X86AddressMode AM;
2790   if (!X86SelectAddress(C, AM))
2791     return 0;
2792   unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2793   const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2794   unsigned ResultReg = createResultReg(RC);
2795   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2796                          TII.get(Opc), ResultReg), AM);
2797   return ResultReg;
2798 }
2799
2800 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2801   MVT VT;
2802   if (!isTypeLegal(CF->getType(), VT))
2803     return 0;
2804
2805   // Get opcode and regclass for the given zero.
2806   unsigned Opc = 0;
2807   const TargetRegisterClass *RC = nullptr;
2808   switch (VT.SimpleTy) {
2809   default: return 0;
2810   case MVT::f32:
2811     if (X86ScalarSSEf32) {
2812       Opc = X86::FsFLD0SS;
2813       RC  = &X86::FR32RegClass;
2814     } else {
2815       Opc = X86::LD_Fp032;
2816       RC  = &X86::RFP32RegClass;
2817     }
2818     break;
2819   case MVT::f64:
2820     if (X86ScalarSSEf64) {
2821       Opc = X86::FsFLD0SD;
2822       RC  = &X86::FR64RegClass;
2823     } else {
2824       Opc = X86::LD_Fp064;
2825       RC  = &X86::RFP64RegClass;
2826     }
2827     break;
2828   case MVT::f80:
2829     // No f80 support yet.
2830     return 0;
2831   }
2832
2833   unsigned ResultReg = createResultReg(RC);
2834   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
2835   return ResultReg;
2836 }
2837
2838
2839 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2840                                       const LoadInst *LI) {
2841   const Value *Ptr = LI->getPointerOperand();
2842   X86AddressMode AM;
2843   if (!X86SelectAddress(Ptr, AM))
2844     return false;
2845
2846   const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2847
2848   unsigned Size = DL.getTypeAllocSize(LI->getType());
2849   unsigned Alignment = LI->getAlignment();
2850
2851   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
2852     Alignment = DL.getABITypeAlignment(LI->getType());
2853
2854   SmallVector<MachineOperand, 8> AddrOps;
2855   AM.getFullAddress(AddrOps);
2856
2857   MachineInstr *Result =
2858     XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2859   if (!Result)
2860     return false;
2861
2862   Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
2863   FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2864   MI->eraseFromParent();
2865   return true;
2866 }
2867
2868
2869 namespace llvm {
2870   FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2871                                 const TargetLibraryInfo *libInfo) {
2872     return new X86FastISel(funcInfo, libInfo);
2873   }
2874 }