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