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