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