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