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