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