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