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