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