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