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