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