1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
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;
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.
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();
69 bool fastSelectInstruction(const Instruction *I) override;
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
75 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
76 const LoadInst *LI) override;
78 bool fastLowerArguments() override;
79 bool fastLowerCall(CallLoweringInfo &CLI) override;
80 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
82 #include "X86GenFastISel.inc"
85 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
88 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
89 unsigned &ResultReg, unsigned Alignment = 1);
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,
95 MachineMemOperand *MMO = nullptr, bool Aligned = false);
97 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
100 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
101 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
103 bool X86SelectLoad(const Instruction *I);
105 bool X86SelectStore(const Instruction *I);
107 bool X86SelectRet(const Instruction *I);
109 bool X86SelectCmp(const Instruction *I);
111 bool X86SelectZExt(const Instruction *I);
113 bool X86SelectBranch(const Instruction *I);
115 bool X86SelectShift(const Instruction *I);
117 bool X86SelectDivRem(const Instruction *I);
119 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
121 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
123 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
125 bool X86SelectSelect(const Instruction *I);
127 bool X86SelectTrunc(const Instruction *I);
129 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
130 const TargetRegisterClass *RC);
132 bool X86SelectFPExt(const Instruction *I);
133 bool X86SelectFPTrunc(const Instruction *I);
134 bool X86SelectSIToFP(const Instruction *I);
136 const X86InstrInfo *getInstrInfo() const {
137 return Subtarget->getInstrInfo();
139 const X86TargetMachine *getTargetMachine() const {
140 return static_cast<const X86TargetMachine *>(&TM);
143 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
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;
150 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
152 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
154 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
155 /// computed in an SSE register, not on the X87 floating point stack.
156 bool isScalarFPTypeInSSEReg(EVT VT) const {
157 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
158 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
161 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
163 bool IsMemcpySmall(uint64_t Len);
165 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
166 X86AddressMode SrcAM, uint64_t Len);
168 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
171 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
174 unsigned fastEmitInst_rrrr(unsigned MachineInstOpcode,
175 const TargetRegisterClass *RC, unsigned Op0,
176 bool Op0IsKill, unsigned Op1, bool Op1IsKill,
177 unsigned Op2, bool Op2IsKill, unsigned Op3,
181 } // end anonymous namespace.
183 static std::pair<unsigned, bool>
184 getX86SSEConditionCode(CmpInst::Predicate Predicate) {
186 bool NeedSwap = false;
188 // SSE Condition code mapping:
198 default: llvm_unreachable("Unexpected predicate");
199 case CmpInst::FCMP_OEQ: CC = 0; break;
200 case CmpInst::FCMP_OGT: NeedSwap = true; LLVM_FALLTHROUGH;
201 case CmpInst::FCMP_OLT: CC = 1; break;
202 case CmpInst::FCMP_OGE: NeedSwap = true; LLVM_FALLTHROUGH;
203 case CmpInst::FCMP_OLE: CC = 2; break;
204 case CmpInst::FCMP_UNO: CC = 3; break;
205 case CmpInst::FCMP_UNE: CC = 4; break;
206 case CmpInst::FCMP_ULE: NeedSwap = true; LLVM_FALLTHROUGH;
207 case CmpInst::FCMP_UGE: CC = 5; break;
208 case CmpInst::FCMP_ULT: NeedSwap = true; LLVM_FALLTHROUGH;
209 case CmpInst::FCMP_UGT: CC = 6; break;
210 case CmpInst::FCMP_ORD: CC = 7; break;
211 case CmpInst::FCMP_UEQ:
212 case CmpInst::FCMP_ONE: CC = 8; break;
215 return std::make_pair(CC, NeedSwap);
218 /// \brief Adds a complex addressing mode to the given machine instr builder.
219 /// Note, this will constrain the index register. If its not possible to
220 /// constrain the given index register, then a new one will be created. The
221 /// IndexReg field of the addressing mode will be updated to match in this case.
222 const MachineInstrBuilder &
223 X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
224 X86AddressMode &AM) {
225 // First constrain the index register. It needs to be a GR64_NOSP.
226 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
227 MIB->getNumOperands() +
229 return ::addFullAddress(MIB, AM);
232 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
233 /// into the user. The condition code will only be updated on success.
234 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
236 if (!isa<ExtractValueInst>(Cond))
239 const auto *EV = cast<ExtractValueInst>(Cond);
240 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
243 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
245 const Function *Callee = II->getCalledFunction();
247 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
248 if (!isTypeLegal(RetTy, RetVT))
251 if (RetVT != MVT::i32 && RetVT != MVT::i64)
255 switch (II->getIntrinsicID()) {
256 default: return false;
257 case Intrinsic::sadd_with_overflow:
258 case Intrinsic::ssub_with_overflow:
259 case Intrinsic::smul_with_overflow:
260 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
261 case Intrinsic::uadd_with_overflow:
262 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
265 // Check if both instructions are in the same basic block.
266 if (II->getParent() != I->getParent())
269 // Make sure nothing is in the way
270 BasicBlock::const_iterator Start(I);
271 BasicBlock::const_iterator End(II);
272 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
273 // We only expect extractvalue instructions between the intrinsic and the
274 // instruction to be selected.
275 if (!isa<ExtractValueInst>(Itr))
278 // Check that the extractvalue operand comes from the intrinsic.
279 const auto *EVI = cast<ExtractValueInst>(Itr);
280 if (EVI->getAggregateOperand() != II)
288 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
289 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
290 if (evt == MVT::Other || !evt.isSimple())
291 // Unhandled type. Halt "fast" selection and bail.
294 VT = evt.getSimpleVT();
295 // For now, require SSE/SSE2 for performing floating-point operations,
296 // since x87 requires additional work.
297 if (VT == MVT::f64 && !X86ScalarSSEf64)
299 if (VT == MVT::f32 && !X86ScalarSSEf32)
301 // Similarly, no f80 support yet.
304 // We only handle legal types. For example, on x86-32 the instruction
305 // selector contains all of the 64-bit instructions from x86-64,
306 // under the assumption that i64 won't be used if the target doesn't
308 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
311 #include "X86GenCallingConv.inc"
313 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
314 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
315 /// Return true and the result register by reference if it is possible.
316 bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
317 MachineMemOperand *MMO, unsigned &ResultReg,
318 unsigned Alignment) {
319 bool HasSSE41 = Subtarget->hasSSE41();
320 bool HasAVX = Subtarget->hasAVX();
321 bool HasAVX2 = Subtarget->hasAVX2();
322 bool HasAVX512 = Subtarget->hasAVX512();
323 bool HasVLX = Subtarget->hasVLX();
324 bool IsNonTemporal = MMO && MMO->isNonTemporal();
326 // Get opcode and regclass of the output for the given load instruction.
328 const TargetRegisterClass *RC = nullptr;
329 switch (VT.getSimpleVT().SimpleTy) {
330 default: return false;
332 // TODO: Support this properly.
333 if (Subtarget->hasAVX512())
338 RC = &X86::GR8RegClass;
342 RC = &X86::GR16RegClass;
346 RC = &X86::GR32RegClass;
349 // Must be in x86-64 mode.
351 RC = &X86::GR64RegClass;
354 if (X86ScalarSSEf32) {
355 Opc = HasAVX512 ? X86::VMOVSSZrm : HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
356 RC = &X86::FR32RegClass;
359 RC = &X86::RFP32RegClass;
363 if (X86ScalarSSEf64) {
364 Opc = HasAVX512 ? X86::VMOVSDZrm : HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
365 RC = &X86::FR64RegClass;
368 RC = &X86::RFP64RegClass;
372 // No f80 support yet.
375 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
376 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
377 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
378 else if (Alignment >= 16)
379 Opc = HasVLX ? X86::VMOVAPSZ128rm :
380 HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
382 Opc = HasVLX ? X86::VMOVUPSZ128rm :
383 HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
384 RC = &X86::VR128RegClass;
387 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
388 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
389 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
390 else if (Alignment >= 16)
391 Opc = HasVLX ? X86::VMOVAPDZ128rm :
392 HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
394 Opc = HasVLX ? X86::VMOVUPDZ128rm :
395 HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
396 RC = &X86::VR128RegClass;
402 if (IsNonTemporal && Alignment >= 16)
403 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
404 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
405 else if (Alignment >= 16)
406 Opc = HasVLX ? X86::VMOVDQA64Z128rm :
407 HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
409 Opc = HasVLX ? X86::VMOVDQU64Z128rm :
410 HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
411 RC = &X86::VR128RegClass;
415 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
416 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
417 else if (IsNonTemporal && Alignment >= 16)
418 return false; // Force split for X86::VMOVNTDQArm
419 else if (Alignment >= 32)
420 Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
422 Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
423 RC = &X86::VR256RegClass;
427 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
428 Opc = X86::VMOVNTDQAYrm;
429 else if (IsNonTemporal && Alignment >= 16)
430 return false; // Force split for X86::VMOVNTDQArm
431 else if (Alignment >= 32)
432 Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
434 Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
435 RC = &X86::VR256RegClass;
442 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
443 Opc = X86::VMOVNTDQAYrm;
444 else if (IsNonTemporal && Alignment >= 16)
445 return false; // Force split for X86::VMOVNTDQArm
446 else if (Alignment >= 32)
447 Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
449 Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
450 RC = &X86::VR256RegClass;
454 if (IsNonTemporal && Alignment >= 64)
455 Opc = X86::VMOVNTDQAZrm;
457 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
458 RC = &X86::VR512RegClass;
462 if (IsNonTemporal && Alignment >= 64)
463 Opc = X86::VMOVNTDQAZrm;
465 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
466 RC = &X86::VR512RegClass;
473 // Note: There are a lot more choices based on type with AVX-512, but
474 // there's really no advantage when the load isn't masked.
475 if (IsNonTemporal && Alignment >= 64)
476 Opc = X86::VMOVNTDQAZrm;
478 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
479 RC = &X86::VR512RegClass;
483 ResultReg = createResultReg(RC);
484 MachineInstrBuilder MIB =
485 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
486 addFullAddress(MIB, AM);
488 MIB->addMemOperand(*FuncInfo.MF, MMO);
492 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
493 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
494 /// and a displacement offset, or a GlobalAddress,
495 /// i.e. V. Return true if it is possible.
496 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
498 MachineMemOperand *MMO, bool Aligned) {
499 bool HasSSE1 = Subtarget->hasSSE1();
500 bool HasSSE2 = Subtarget->hasSSE2();
501 bool HasSSE4A = Subtarget->hasSSE4A();
502 bool HasAVX = Subtarget->hasAVX();
503 bool HasAVX512 = Subtarget->hasAVX512();
504 bool HasVLX = Subtarget->hasVLX();
505 bool IsNonTemporal = MMO && MMO->isNonTemporal();
507 // Get opcode and regclass of the output for the given store instruction.
509 switch (VT.getSimpleVT().SimpleTy) {
510 case MVT::f80: // No f80 support yet.
511 default: return false;
513 // In case ValReg is a K register, COPY to a GPR
514 if (MRI.getRegClass(ValReg) == &X86::VK1RegClass) {
515 unsigned KValReg = ValReg;
516 ValReg = createResultReg(&X86::GR32RegClass);
517 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
518 TII.get(TargetOpcode::COPY), ValReg)
520 ValReg = fastEmitInst_extractsubreg(MVT::i8, ValReg, /*Kill=*/true,
523 // Mask out all but lowest bit.
524 unsigned AndResult = createResultReg(&X86::GR8RegClass);
525 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
526 TII.get(X86::AND8ri), AndResult)
527 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
529 LLVM_FALLTHROUGH; // handle i1 as i8.
531 case MVT::i8: Opc = X86::MOV8mr; break;
532 case MVT::i16: Opc = X86::MOV16mr; break;
534 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
537 // Must be in x86-64 mode.
538 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
541 if (X86ScalarSSEf32) {
542 if (IsNonTemporal && HasSSE4A)
545 Opc = HasAVX512 ? X86::VMOVSSZmr :
546 HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
551 if (X86ScalarSSEf32) {
552 if (IsNonTemporal && HasSSE4A)
555 Opc = HasAVX512 ? X86::VMOVSDZmr :
556 HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
561 Opc = (IsNonTemporal && HasSSE1) ? X86::MMX_MOVNTQmr : X86::MMX_MOVQ64mr;
566 Opc = HasVLX ? X86::VMOVNTPSZ128mr :
567 HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
569 Opc = HasVLX ? X86::VMOVAPSZ128mr :
570 HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
572 Opc = HasVLX ? X86::VMOVUPSZ128mr :
573 HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
578 Opc = HasVLX ? X86::VMOVNTPDZ128mr :
579 HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
581 Opc = HasVLX ? X86::VMOVAPDZ128mr :
582 HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
584 Opc = HasVLX ? X86::VMOVUPDZ128mr :
585 HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
593 Opc = HasVLX ? X86::VMOVNTDQZ128mr :
594 HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
596 Opc = HasVLX ? X86::VMOVDQA64Z128mr :
597 HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
599 Opc = HasVLX ? X86::VMOVDQU64Z128mr :
600 HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
606 Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
608 Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
610 Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
616 Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
618 Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
620 Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
629 Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
631 Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
633 Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
638 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
640 Opc = X86::VMOVUPSZmr;
645 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
647 Opc = X86::VMOVUPDZmr;
654 // Note: There are a lot more choices based on type with AVX-512, but
655 // there's really no advantage when the store isn't masked.
657 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
659 Opc = X86::VMOVDQU64Zmr;
663 const MCInstrDesc &Desc = TII.get(Opc);
664 // Some of the instructions in the previous switch use FR128 instead
665 // of FR32 for ValReg. Make sure the register we feed the instruction
666 // matches its register class constraints.
667 // Note: This is fine to do a copy from FR32 to FR128, this is the
668 // same registers behind the scene and actually why it did not trigger
670 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
671 MachineInstrBuilder MIB =
672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
673 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
675 MIB->addMemOperand(*FuncInfo.MF, MMO);
680 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
682 MachineMemOperand *MMO, bool Aligned) {
683 // Handle 'null' like i32/i64 0.
684 if (isa<ConstantPointerNull>(Val))
685 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
687 // If this is a store of a simple constant, fold the constant into the store.
688 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
691 switch (VT.getSimpleVT().SimpleTy) {
695 LLVM_FALLTHROUGH; // Handle as i8.
696 case MVT::i8: Opc = X86::MOV8mi; break;
697 case MVT::i16: Opc = X86::MOV16mi; break;
698 case MVT::i32: Opc = X86::MOV32mi; break;
700 // Must be a 32-bit sign extended value.
701 if (isInt<32>(CI->getSExtValue()))
702 Opc = X86::MOV64mi32;
707 MachineInstrBuilder MIB =
708 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
709 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
710 : CI->getZExtValue());
712 MIB->addMemOperand(*FuncInfo.MF, MMO);
717 unsigned ValReg = getRegForValue(Val);
721 bool ValKill = hasTrivialKill(Val);
722 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
725 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
726 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
727 /// ISD::SIGN_EXTEND).
728 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
729 unsigned Src, EVT SrcVT,
730 unsigned &ResultReg) {
731 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
732 Src, /*TODO: Kill=*/false);
740 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
741 // Handle constant address.
742 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
743 // Can't handle alternate code models yet.
744 if (TM.getCodeModel() != CodeModel::Small)
747 // Can't handle TLS yet.
748 if (GV->isThreadLocal())
751 // RIP-relative addresses can't have additional register operands, so if
752 // we've already folded stuff into the addressing mode, just force the
753 // global value into its own register, which we can use as the basereg.
754 if (!Subtarget->isPICStyleRIPRel() ||
755 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
756 // Okay, we've committed to selecting this global. Set up the address.
759 // Allow the subtarget to classify the global.
760 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
762 // If this reference is relative to the pic base, set it now.
763 if (isGlobalRelativeToPICBase(GVFlags)) {
764 // FIXME: How do we know Base.Reg is free??
765 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
768 // Unless the ABI requires an extra load, return a direct reference to
770 if (!isGlobalStubReference(GVFlags)) {
771 if (Subtarget->isPICStyleRIPRel()) {
772 // Use rip-relative addressing if we can. Above we verified that the
773 // base and index registers are unused.
774 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
775 AM.Base.Reg = X86::RIP;
777 AM.GVOpFlags = GVFlags;
781 // Ok, we need to do a load from a stub. If we've already loaded from
782 // this stub, reuse the loaded pointer, otherwise emit the load now.
783 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
785 if (I != LocalValueMap.end() && I->second != 0) {
788 // Issue load from stub.
790 const TargetRegisterClass *RC = nullptr;
791 X86AddressMode StubAM;
792 StubAM.Base.Reg = AM.Base.Reg;
794 StubAM.GVOpFlags = GVFlags;
796 // Prepare for inserting code in the local-value area.
797 SavePoint SaveInsertPt = enterLocalValueArea();
799 if (TLI.getPointerTy(DL) == MVT::i64) {
801 RC = &X86::GR64RegClass;
803 if (Subtarget->isPICStyleRIPRel())
804 StubAM.Base.Reg = X86::RIP;
807 RC = &X86::GR32RegClass;
810 LoadReg = createResultReg(RC);
811 MachineInstrBuilder LoadMI =
812 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
813 addFullAddress(LoadMI, StubAM);
815 // Ok, back to normal mode.
816 leaveLocalValueArea(SaveInsertPt);
818 // Prevent loading GV stub multiple times in same MBB.
819 LocalValueMap[V] = LoadReg;
822 // Now construct the final address. Note that the Disp, Scale,
823 // and Index values may already be set here.
824 AM.Base.Reg = LoadReg;
830 // If all else fails, try to materialize the value in a register.
831 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
832 if (AM.Base.Reg == 0) {
833 AM.Base.Reg = getRegForValue(V);
834 return AM.Base.Reg != 0;
836 if (AM.IndexReg == 0) {
837 assert(AM.Scale == 1 && "Scale with no index!");
838 AM.IndexReg = getRegForValue(V);
839 return AM.IndexReg != 0;
846 /// X86SelectAddress - Attempt to fill in an address from the given value.
848 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
849 SmallVector<const Value *, 32> GEPs;
851 const User *U = nullptr;
852 unsigned Opcode = Instruction::UserOp1;
853 if (const Instruction *I = dyn_cast<Instruction>(V)) {
854 // Don't walk into other basic blocks; it's possible we haven't
855 // visited them yet, so the instructions may not yet be assigned
856 // virtual registers.
857 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
858 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
859 Opcode = I->getOpcode();
862 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
863 Opcode = C->getOpcode();
867 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
868 if (Ty->getAddressSpace() > 255)
869 // Fast instruction selection doesn't support the special
875 case Instruction::BitCast:
876 // Look past bitcasts.
877 return X86SelectAddress(U->getOperand(0), AM);
879 case Instruction::IntToPtr:
880 // Look past no-op inttoptrs.
881 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
882 TLI.getPointerTy(DL))
883 return X86SelectAddress(U->getOperand(0), AM);
886 case Instruction::PtrToInt:
887 // Look past no-op ptrtoints.
888 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
889 return X86SelectAddress(U->getOperand(0), AM);
892 case Instruction::Alloca: {
893 // Do static allocas.
894 const AllocaInst *A = cast<AllocaInst>(V);
895 DenseMap<const AllocaInst *, int>::iterator SI =
896 FuncInfo.StaticAllocaMap.find(A);
897 if (SI != FuncInfo.StaticAllocaMap.end()) {
898 AM.BaseType = X86AddressMode::FrameIndexBase;
899 AM.Base.FrameIndex = SI->second;
905 case Instruction::Add: {
906 // Adds of constants are common and easy enough.
907 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
908 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
909 // They have to fit in the 32-bit signed displacement field though.
910 if (isInt<32>(Disp)) {
911 AM.Disp = (uint32_t)Disp;
912 return X86SelectAddress(U->getOperand(0), AM);
918 case Instruction::GetElementPtr: {
919 X86AddressMode SavedAM = AM;
921 // Pattern-match simple GEPs.
922 uint64_t Disp = (int32_t)AM.Disp;
923 unsigned IndexReg = AM.IndexReg;
924 unsigned Scale = AM.Scale;
925 gep_type_iterator GTI = gep_type_begin(U);
926 // Iterate through the indices, folding what we can. Constants can be
927 // folded, and one dynamic index can be handled, if the scale is supported.
928 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
929 i != e; ++i, ++GTI) {
930 const Value *Op = *i;
931 if (StructType *STy = GTI.getStructTypeOrNull()) {
932 const StructLayout *SL = DL.getStructLayout(STy);
933 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
937 // A array/variable index is always of the form i*S where S is the
938 // constant scale size. See if we can push the scale into immediates.
939 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
941 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
942 // Constant-offset addressing.
943 Disp += CI->getSExtValue() * S;
946 if (canFoldAddIntoGEP(U, Op)) {
947 // A compatible add with a constant operand. Fold the constant.
949 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
950 Disp += CI->getSExtValue() * S;
951 // Iterate on the other operand.
952 Op = cast<AddOperator>(Op)->getOperand(0);
956 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
957 (S == 1 || S == 2 || S == 4 || S == 8)) {
958 // Scaled-index addressing.
960 IndexReg = getRegForGEPIndex(Op).first;
966 goto unsupported_gep;
970 // Check for displacement overflow.
971 if (!isInt<32>(Disp))
974 AM.IndexReg = IndexReg;
976 AM.Disp = (uint32_t)Disp;
979 if (const GetElementPtrInst *GEP =
980 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
981 // Ok, the GEP indices were covered by constant-offset and scaled-index
982 // addressing. Update the address state and move on to examining the base.
985 } else if (X86SelectAddress(U->getOperand(0), AM)) {
989 // If we couldn't merge the gep value into this addr mode, revert back to
990 // our address and just match the value instead of completely failing.
993 for (const Value *I : reverse(GEPs))
994 if (handleConstantAddresses(I, AM))
999 // Ok, the GEP indices weren't all covered.
1004 return handleConstantAddresses(V, AM);
1007 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
1009 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
1010 const User *U = nullptr;
1011 unsigned Opcode = Instruction::UserOp1;
1012 const Instruction *I = dyn_cast<Instruction>(V);
1013 // Record if the value is defined in the same basic block.
1015 // This information is crucial to know whether or not folding an
1016 // operand is valid.
1017 // Indeed, FastISel generates or reuses a virtual register for all
1018 // operands of all instructions it selects. Obviously, the definition and
1019 // its uses must use the same virtual register otherwise the produced
1020 // code is incorrect.
1021 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
1022 // registers for values that are alive across basic blocks. This ensures
1023 // that the values are consistently set between across basic block, even
1024 // if different instruction selection mechanisms are used (e.g., a mix of
1025 // SDISel and FastISel).
1026 // For values local to a basic block, the instruction selection process
1027 // generates these virtual registers with whatever method is appropriate
1028 // for its needs. In particular, FastISel and SDISel do not share the way
1029 // local virtual registers are set.
1030 // Therefore, this is impossible (or at least unsafe) to share values
1031 // between basic blocks unless they use the same instruction selection
1032 // method, which is not guarantee for X86.
1033 // Moreover, things like hasOneUse could not be used accurately, if we
1034 // allow to reference values across basic blocks whereas they are not
1035 // alive across basic blocks initially.
1038 Opcode = I->getOpcode();
1040 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1041 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1042 Opcode = C->getOpcode();
1048 case Instruction::BitCast:
1049 // Look past bitcasts if its operand is in the same BB.
1051 return X86SelectCallAddress(U->getOperand(0), AM);
1054 case Instruction::IntToPtr:
1055 // Look past no-op inttoptrs if its operand is in the same BB.
1057 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1058 TLI.getPointerTy(DL))
1059 return X86SelectCallAddress(U->getOperand(0), AM);
1062 case Instruction::PtrToInt:
1063 // Look past no-op ptrtoints if its operand is in the same BB.
1064 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
1065 return X86SelectCallAddress(U->getOperand(0), AM);
1069 // Handle constant address.
1070 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1071 // Can't handle alternate code models yet.
1072 if (TM.getCodeModel() != CodeModel::Small)
1075 // RIP-relative addresses can't have additional register operands.
1076 if (Subtarget->isPICStyleRIPRel() &&
1077 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1080 // Can't handle DLL Import.
1081 if (GV->hasDLLImportStorageClass())
1084 // Can't handle TLS.
1085 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1086 if (GVar->isThreadLocal())
1089 // Okay, we've committed to selecting this global. Set up the basic address.
1092 // No ABI requires an extra load for anything other than DLLImport, which
1093 // we rejected above. Return a direct reference to the global.
1094 if (Subtarget->isPICStyleRIPRel()) {
1095 // Use rip-relative addressing if we can. Above we verified that the
1096 // base and index registers are unused.
1097 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1098 AM.Base.Reg = X86::RIP;
1100 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
1106 // If all else fails, try to materialize the value in a register.
1107 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1108 if (AM.Base.Reg == 0) {
1109 AM.Base.Reg = getRegForValue(V);
1110 return AM.Base.Reg != 0;
1112 if (AM.IndexReg == 0) {
1113 assert(AM.Scale == 1 && "Scale with no index!");
1114 AM.IndexReg = getRegForValue(V);
1115 return AM.IndexReg != 0;
1123 /// X86SelectStore - Select and emit code to implement store instructions.
1124 bool X86FastISel::X86SelectStore(const Instruction *I) {
1125 // Atomic stores need special handling.
1126 const StoreInst *S = cast<StoreInst>(I);
1131 const Value *PtrV = I->getOperand(1);
1132 if (TLI.supportSwiftError()) {
1133 // Swifterror values can come from either a function parameter with
1134 // swifterror attribute or an alloca with swifterror attribute.
1135 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1136 if (Arg->hasSwiftErrorAttr())
1140 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1141 if (Alloca->isSwiftError())
1146 const Value *Val = S->getValueOperand();
1147 const Value *Ptr = S->getPointerOperand();
1150 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1153 unsigned Alignment = S->getAlignment();
1154 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1155 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1156 Alignment = ABIAlignment;
1157 bool Aligned = Alignment >= ABIAlignment;
1160 if (!X86SelectAddress(Ptr, AM))
1163 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1166 /// X86SelectRet - Select and emit code to implement ret instructions.
1167 bool X86FastISel::X86SelectRet(const Instruction *I) {
1168 const ReturnInst *Ret = cast<ReturnInst>(I);
1169 const Function &F = *I->getParent()->getParent();
1170 const X86MachineFunctionInfo *X86MFInfo =
1171 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1173 if (!FuncInfo.CanLowerReturn)
1176 if (TLI.supportSwiftError() &&
1177 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1180 if (TLI.supportSplitCSR(FuncInfo.MF))
1183 CallingConv::ID CC = F.getCallingConv();
1184 if (CC != CallingConv::C &&
1185 CC != CallingConv::Fast &&
1186 CC != CallingConv::X86_FastCall &&
1187 CC != CallingConv::X86_StdCall &&
1188 CC != CallingConv::X86_ThisCall &&
1189 CC != CallingConv::X86_64_SysV &&
1190 CC != CallingConv::Win64)
1193 // Don't handle popping bytes if they don't fit the ret's immediate.
1194 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
1197 // fastcc with -tailcallopt is intended to provide a guaranteed
1198 // tail call optimization. Fastisel doesn't know how to do that.
1199 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1202 // Let SDISel handle vararg functions.
1206 // Build a list of return value registers.
1207 SmallVector<unsigned, 4> RetRegs;
1209 if (Ret->getNumOperands() > 0) {
1210 SmallVector<ISD::OutputArg, 4> Outs;
1211 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
1213 // Analyze operands of the call, assigning locations to each operand.
1214 SmallVector<CCValAssign, 16> ValLocs;
1215 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1216 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1218 const Value *RV = Ret->getOperand(0);
1219 unsigned Reg = getRegForValue(RV);
1223 // Only handle a single return value for now.
1224 if (ValLocs.size() != 1)
1227 CCValAssign &VA = ValLocs[0];
1229 // Don't bother handling odd stuff for now.
1230 if (VA.getLocInfo() != CCValAssign::Full)
1232 // Only handle register returns for now.
1236 // The calling-convention tables for x87 returns don't tell
1238 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1241 unsigned SrcReg = Reg + VA.getValNo();
1242 EVT SrcVT = TLI.getValueType(DL, RV->getType());
1243 EVT DstVT = VA.getValVT();
1244 // Special handling for extended integers.
1245 if (SrcVT != DstVT) {
1246 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1249 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1252 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1254 if (SrcVT == MVT::i1) {
1255 if (Outs[0].Flags.isSExt())
1257 // In case SrcReg is a K register, COPY to a GPR
1258 if (MRI.getRegClass(SrcReg) == &X86::VK1RegClass) {
1259 unsigned KSrcReg = SrcReg;
1260 SrcReg = createResultReg(&X86::GR32RegClass);
1261 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1262 TII.get(TargetOpcode::COPY), SrcReg)
1264 SrcReg = fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
1267 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1270 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1272 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1273 SrcReg, /*TODO: Kill=*/false);
1277 unsigned DstReg = VA.getLocReg();
1278 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1279 // Avoid a cross-class copy. This is very unlikely.
1280 if (!SrcRC->contains(DstReg))
1282 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1283 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1285 // Add register to return instruction.
1286 RetRegs.push_back(VA.getLocReg());
1289 // Swift calling convention does not require we copy the sret argument
1290 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1292 // All x86 ABIs require that for returning structs by value we copy
1293 // the sret argument into %rax/%eax (depending on ABI) for the return.
1294 // We saved the argument into a virtual register in the entry block,
1295 // so now we copy the value out and into %rax/%eax.
1296 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
1297 unsigned Reg = X86MFInfo->getSRetReturnReg();
1299 "SRetReturnReg should have been set in LowerFormalArguments()!");
1300 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1301 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1302 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1303 RetRegs.push_back(RetReg);
1306 // Now emit the RET.
1307 MachineInstrBuilder MIB;
1308 if (X86MFInfo->getBytesToPopOnReturn()) {
1309 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1310 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1311 .addImm(X86MFInfo->getBytesToPopOnReturn());
1313 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1314 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1316 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1317 MIB.addReg(RetRegs[i], RegState::Implicit);
1321 /// X86SelectLoad - Select and emit code to implement load instructions.
1323 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1324 const LoadInst *LI = cast<LoadInst>(I);
1326 // Atomic loads need special handling.
1330 const Value *SV = I->getOperand(0);
1331 if (TLI.supportSwiftError()) {
1332 // Swifterror values can come from either a function parameter with
1333 // swifterror attribute or an alloca with swifterror attribute.
1334 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1335 if (Arg->hasSwiftErrorAttr())
1339 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1340 if (Alloca->isSwiftError())
1346 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1349 const Value *Ptr = LI->getPointerOperand();
1352 if (!X86SelectAddress(Ptr, AM))
1355 unsigned Alignment = LI->getAlignment();
1356 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1357 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1358 Alignment = ABIAlignment;
1360 unsigned ResultReg = 0;
1361 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1365 updateValueMap(I, ResultReg);
1369 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1370 bool HasAVX = Subtarget->hasAVX();
1371 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1372 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1374 switch (VT.getSimpleVT().SimpleTy) {
1376 case MVT::i8: return X86::CMP8rr;
1377 case MVT::i16: return X86::CMP16rr;
1378 case MVT::i32: return X86::CMP32rr;
1379 case MVT::i64: return X86::CMP64rr;
1381 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1383 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1387 /// If we have a comparison with RHS as the RHS of the comparison, return an
1388 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1389 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1390 int64_t Val = RHSC->getSExtValue();
1391 switch (VT.getSimpleVT().SimpleTy) {
1392 // Otherwise, we can't fold the immediate into this comparison.
1399 return X86::CMP16ri8;
1400 return X86::CMP16ri;
1403 return X86::CMP32ri8;
1404 return X86::CMP32ri;
1407 return X86::CMP64ri8;
1408 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1411 return X86::CMP64ri32;
1416 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1417 const DebugLoc &CurDbgLoc) {
1418 unsigned Op0Reg = getRegForValue(Op0);
1419 if (Op0Reg == 0) return false;
1421 // Handle 'null' like i32/i64 0.
1422 if (isa<ConstantPointerNull>(Op1))
1423 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1425 // We have two options: compare with register or immediate. If the RHS of
1426 // the compare is an immediate that we can fold into this compare, use
1427 // CMPri, otherwise use CMPrr.
1428 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1429 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1432 .addImm(Op1C->getSExtValue());
1437 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1438 if (CompareOpc == 0) return false;
1440 unsigned Op1Reg = getRegForValue(Op1);
1441 if (Op1Reg == 0) return false;
1442 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1449 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1450 const CmpInst *CI = cast<CmpInst>(I);
1453 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1456 if (I->getType()->isIntegerTy(1) && Subtarget->hasAVX512())
1459 // Try to optimize or fold the cmp.
1460 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1461 unsigned ResultReg = 0;
1462 switch (Predicate) {
1464 case CmpInst::FCMP_FALSE: {
1465 ResultReg = createResultReg(&X86::GR32RegClass);
1466 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1468 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1474 case CmpInst::FCMP_TRUE: {
1475 ResultReg = createResultReg(&X86::GR8RegClass);
1476 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1477 ResultReg).addImm(1);
1483 updateValueMap(I, ResultReg);
1487 const Value *LHS = CI->getOperand(0);
1488 const Value *RHS = CI->getOperand(1);
1490 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1491 // We don't have to materialize a zero constant for this case and can just use
1492 // %x again on the RHS.
1493 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1494 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1495 if (RHSC && RHSC->isNullValue())
1499 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1500 static const uint16_t SETFOpcTable[2][3] = {
1501 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1502 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1504 const uint16_t *SETFOpc = nullptr;
1505 switch (Predicate) {
1507 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1508 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1511 ResultReg = createResultReg(&X86::GR8RegClass);
1513 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1516 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1517 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1520 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1522 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1523 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1524 updateValueMap(I, ResultReg);
1530 std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
1531 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1532 unsigned Opc = X86::getSETFromCond(CC);
1535 std::swap(LHS, RHS);
1537 // Emit a compare of LHS/RHS.
1538 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1541 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1542 updateValueMap(I, ResultReg);
1546 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1547 EVT DstVT = TLI.getValueType(DL, I->getType());
1548 if (!TLI.isTypeLegal(DstVT))
1551 unsigned ResultReg = getRegForValue(I->getOperand(0));
1555 // Handle zero-extension from i1 to i8, which is common.
1556 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1557 if (SrcVT == MVT::i1) {
1558 // In case ResultReg is a K register, COPY to a GPR
1559 if (MRI.getRegClass(ResultReg) == &X86::VK1RegClass) {
1560 unsigned KResultReg = ResultReg;
1561 ResultReg = createResultReg(&X86::GR32RegClass);
1562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1563 TII.get(TargetOpcode::COPY), ResultReg)
1564 .addReg(KResultReg);
1565 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1569 // Set the high bits to zero.
1570 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1577 if (DstVT == MVT::i64) {
1578 // Handle extension to 64-bits via sub-register shenanigans.
1581 switch (SrcVT.SimpleTy) {
1582 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1583 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1584 case MVT::i32: MovInst = X86::MOV32rr; break;
1585 default: llvm_unreachable("Unexpected zext to i64 source type");
1588 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1589 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1592 ResultReg = createResultReg(&X86::GR64RegClass);
1593 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1595 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1596 } else if (DstVT != MVT::i8) {
1597 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1598 ResultReg, /*Kill=*/true);
1603 updateValueMap(I, ResultReg);
1607 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1608 // Unconditional branches are selected by tablegen-generated code.
1609 // Handle a conditional branch.
1610 const BranchInst *BI = cast<BranchInst>(I);
1611 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1612 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1614 // Fold the common case of a conditional branch with a comparison
1615 // in the same block (values defined on other blocks may not have
1616 // initialized registers).
1618 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1619 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1620 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1622 // Try to optimize or fold the cmp.
1623 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1624 switch (Predicate) {
1626 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1627 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1630 const Value *CmpLHS = CI->getOperand(0);
1631 const Value *CmpRHS = CI->getOperand(1);
1633 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1635 // We don't have to materialize a zero constant for this case and can just
1636 // use %x again on the RHS.
1637 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1638 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1639 if (CmpRHSC && CmpRHSC->isNullValue())
1643 // Try to take advantage of fallthrough opportunities.
1644 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1645 std::swap(TrueMBB, FalseMBB);
1646 Predicate = CmpInst::getInversePredicate(Predicate);
1649 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1650 // code check. Instead two branch instructions are required to check all
1651 // the flags. First we change the predicate to a supported condition code,
1652 // which will be the first branch. Later one we will emit the second
1654 bool NeedExtraBranch = false;
1655 switch (Predicate) {
1657 case CmpInst::FCMP_OEQ:
1658 std::swap(TrueMBB, FalseMBB);
1660 case CmpInst::FCMP_UNE:
1661 NeedExtraBranch = true;
1662 Predicate = CmpInst::FCMP_ONE;
1668 std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
1669 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1671 BranchOpc = X86::GetCondBranchFromCond(CC);
1673 std::swap(CmpLHS, CmpRHS);
1675 // Emit a compare of the LHS and RHS, setting the flags.
1676 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1679 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1682 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1684 if (NeedExtraBranch) {
1685 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1689 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1692 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1693 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1694 // typically happen for _Bool and C++ bools.
1696 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1697 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1698 unsigned TestOpc = 0;
1699 switch (SourceVT.SimpleTy) {
1701 case MVT::i8: TestOpc = X86::TEST8ri; break;
1702 case MVT::i16: TestOpc = X86::TEST16ri; break;
1703 case MVT::i32: TestOpc = X86::TEST32ri; break;
1704 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1707 unsigned OpReg = getRegForValue(TI->getOperand(0));
1708 if (OpReg == 0) return false;
1710 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1711 .addReg(OpReg).addImm(1);
1713 unsigned JmpOpc = X86::JNE_1;
1714 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1715 std::swap(TrueMBB, FalseMBB);
1719 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1722 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1726 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1727 // Fake request the condition, otherwise the intrinsic might be completely
1729 unsigned TmpReg = getRegForValue(BI->getCondition());
1733 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1735 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1737 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1741 // Otherwise do a clumsy setcc and re-test it.
1742 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1743 // in an explicit cast, so make sure to handle that correctly.
1744 unsigned OpReg = getRegForValue(BI->getCondition());
1745 if (OpReg == 0) return false;
1747 // In case OpReg is a K register, COPY to a GPR
1748 if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) {
1749 unsigned KOpReg = OpReg;
1750 OpReg = createResultReg(&X86::GR32RegClass);
1751 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1752 TII.get(TargetOpcode::COPY), OpReg)
1754 OpReg = fastEmitInst_extractsubreg(MVT::i8, OpReg, /*Kill=*/true,
1757 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1760 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1762 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1766 bool X86FastISel::X86SelectShift(const Instruction *I) {
1767 unsigned CReg = 0, OpReg = 0;
1768 const TargetRegisterClass *RC = nullptr;
1769 if (I->getType()->isIntegerTy(8)) {
1771 RC = &X86::GR8RegClass;
1772 switch (I->getOpcode()) {
1773 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1774 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1775 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1776 default: return false;
1778 } else if (I->getType()->isIntegerTy(16)) {
1780 RC = &X86::GR16RegClass;
1781 switch (I->getOpcode()) {
1782 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1783 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1784 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1785 default: return false;
1787 } else if (I->getType()->isIntegerTy(32)) {
1789 RC = &X86::GR32RegClass;
1790 switch (I->getOpcode()) {
1791 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1792 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1793 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1794 default: return false;
1796 } else if (I->getType()->isIntegerTy(64)) {
1798 RC = &X86::GR64RegClass;
1799 switch (I->getOpcode()) {
1800 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1801 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1802 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1803 default: return false;
1810 if (!isTypeLegal(I->getType(), VT))
1813 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1814 if (Op0Reg == 0) return false;
1816 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1817 if (Op1Reg == 0) return false;
1818 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1819 CReg).addReg(Op1Reg);
1821 // The shift instruction uses X86::CL. If we defined a super-register
1822 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1823 if (CReg != X86::CL)
1824 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1825 TII.get(TargetOpcode::KILL), X86::CL)
1826 .addReg(CReg, RegState::Kill);
1828 unsigned ResultReg = createResultReg(RC);
1829 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1831 updateValueMap(I, ResultReg);
1835 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1836 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1837 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1838 const static bool S = true; // IsSigned
1839 const static bool U = false; // !IsSigned
1840 const static unsigned Copy = TargetOpcode::COPY;
1841 // For the X86 DIV/IDIV instruction, in most cases the dividend
1842 // (numerator) must be in a specific register pair highreg:lowreg,
1843 // producing the quotient in lowreg and the remainder in highreg.
1844 // For most data types, to set up the instruction, the dividend is
1845 // copied into lowreg, and lowreg is sign-extended or zero-extended
1846 // into highreg. The exception is i8, where the dividend is defined
1847 // as a single register rather than a register pair, and we
1848 // therefore directly sign-extend or zero-extend the dividend into
1849 // lowreg, instead of copying, and ignore the highreg.
1850 const static struct DivRemEntry {
1851 // The following portion depends only on the data type.
1852 const TargetRegisterClass *RC;
1853 unsigned LowInReg; // low part of the register pair
1854 unsigned HighInReg; // high part of the register pair
1855 // The following portion depends on both the data type and the operation.
1856 struct DivRemResult {
1857 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1858 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1859 // highreg, or copying a zero into highreg.
1860 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1861 // zero/sign-extending into lowreg for i8.
1862 unsigned DivRemResultReg; // Register containing the desired result.
1863 bool IsOpSigned; // Whether to use signed or unsigned form.
1864 } ResultTable[NumOps];
1865 } OpTable[NumTypes] = {
1866 { &X86::GR8RegClass, X86::AX, 0, {
1867 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1868 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1869 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1870 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1873 { &X86::GR16RegClass, X86::AX, X86::DX, {
1874 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1875 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1876 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1877 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1880 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1881 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1882 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1883 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1884 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1887 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1888 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1889 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1890 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1891 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1897 if (!isTypeLegal(I->getType(), VT))
1900 unsigned TypeIndex, OpIndex;
1901 switch (VT.SimpleTy) {
1902 default: return false;
1903 case MVT::i8: TypeIndex = 0; break;
1904 case MVT::i16: TypeIndex = 1; break;
1905 case MVT::i32: TypeIndex = 2; break;
1906 case MVT::i64: TypeIndex = 3;
1907 if (!Subtarget->is64Bit())
1912 switch (I->getOpcode()) {
1913 default: llvm_unreachable("Unexpected div/rem opcode");
1914 case Instruction::SDiv: OpIndex = 0; break;
1915 case Instruction::SRem: OpIndex = 1; break;
1916 case Instruction::UDiv: OpIndex = 2; break;
1917 case Instruction::URem: OpIndex = 3; break;
1920 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1921 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1922 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1925 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1929 // Move op0 into low-order input register.
1930 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1931 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1932 // Zero-extend or sign-extend into high-order input register.
1933 if (OpEntry.OpSignExtend) {
1934 if (OpEntry.IsOpSigned)
1935 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1936 TII.get(OpEntry.OpSignExtend));
1938 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1939 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1940 TII.get(X86::MOV32r0), Zero32);
1942 // Copy the zero into the appropriate sub/super/identical physical
1943 // register. Unfortunately the operations needed are not uniform enough
1944 // to fit neatly into the table above.
1945 if (VT == MVT::i16) {
1946 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1947 TII.get(Copy), TypeEntry.HighInReg)
1948 .addReg(Zero32, 0, X86::sub_16bit);
1949 } else if (VT == MVT::i32) {
1950 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1951 TII.get(Copy), TypeEntry.HighInReg)
1953 } else if (VT == MVT::i64) {
1954 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1955 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1956 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1960 // Generate the DIV/IDIV instruction.
1961 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1962 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1963 // For i8 remainder, we can't reference AH directly, as we'll end
1964 // up with bogus copies like %R9B = COPY %AH. Reference AX
1965 // instead to prevent AH references in a REX instruction.
1967 // The current assumption of the fast register allocator is that isel
1968 // won't generate explicit references to the GPR8_NOREX registers. If
1969 // the allocator and/or the backend get enhanced to be more robust in
1970 // that regard, this can be, and should be, removed.
1971 unsigned ResultReg = 0;
1972 if ((I->getOpcode() == Instruction::SRem ||
1973 I->getOpcode() == Instruction::URem) &&
1974 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1975 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1976 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1977 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1978 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1980 // Shift AX right by 8 bits instead of using AH.
1981 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1982 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1984 // Now reference the 8-bit subreg of the result.
1985 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1986 /*Kill=*/true, X86::sub_8bit);
1988 // Copy the result out of the physreg if we haven't already.
1990 ResultReg = createResultReg(TypeEntry.RC);
1991 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1992 .addReg(OpEntry.DivRemResultReg);
1994 updateValueMap(I, ResultReg);
1999 /// \brief Emit a conditional move instruction (if the are supported) to lower
2001 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
2002 // Check if the subtarget supports these instructions.
2003 if (!Subtarget->hasCMov())
2006 // FIXME: Add support for i8.
2007 if (RetVT < MVT::i16 || RetVT > MVT::i64)
2010 const Value *Cond = I->getOperand(0);
2011 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2012 bool NeedTest = true;
2013 X86::CondCode CC = X86::COND_NE;
2015 // Optimize conditions coming from a compare if both instructions are in the
2016 // same basic block (values defined in other basic blocks may not have
2017 // initialized registers).
2018 const auto *CI = dyn_cast<CmpInst>(Cond);
2019 if (CI && (CI->getParent() == I->getParent())) {
2020 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2022 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
2023 static const uint16_t SETFOpcTable[2][3] = {
2024 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
2025 { X86::SETPr, X86::SETNEr, X86::OR8rr }
2027 const uint16_t *SETFOpc = nullptr;
2028 switch (Predicate) {
2030 case CmpInst::FCMP_OEQ:
2031 SETFOpc = &SETFOpcTable[0][0];
2032 Predicate = CmpInst::ICMP_NE;
2034 case CmpInst::FCMP_UNE:
2035 SETFOpc = &SETFOpcTable[1][0];
2036 Predicate = CmpInst::ICMP_NE;
2041 std::tie(CC, NeedSwap) = X86::getX86ConditionCode(Predicate);
2042 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
2044 const Value *CmpLHS = CI->getOperand(0);
2045 const Value *CmpRHS = CI->getOperand(1);
2047 std::swap(CmpLHS, CmpRHS);
2049 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2050 // Emit a compare of the LHS and RHS, setting the flags.
2051 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2055 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
2056 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
2057 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
2059 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
2061 auto const &II = TII.get(SETFOpc[2]);
2062 if (II.getNumDefs()) {
2063 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
2064 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
2065 .addReg(FlagReg2).addReg(FlagReg1);
2067 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2068 .addReg(FlagReg2).addReg(FlagReg1);
2072 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2073 // Fake request the condition, otherwise the intrinsic might be completely
2075 unsigned TmpReg = getRegForValue(Cond);
2083 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2084 // garbage. Indeed, only the less significant bit is supposed to be
2085 // accurate. If we read more than the lsb, we may see non-zero values
2086 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2087 // the select. This is achieved by performing TEST against 1.
2088 unsigned CondReg = getRegForValue(Cond);
2091 bool CondIsKill = hasTrivialKill(Cond);
2093 // In case OpReg is a K register, COPY to a GPR
2094 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2095 unsigned KCondReg = CondReg;
2096 CondReg = createResultReg(&X86::GR32RegClass);
2097 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2098 TII.get(TargetOpcode::COPY), CondReg)
2099 .addReg(KCondReg, getKillRegState(CondIsKill));
2100 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, /*Kill=*/true,
2103 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2104 .addReg(CondReg, getKillRegState(CondIsKill))
2108 const Value *LHS = I->getOperand(1);
2109 const Value *RHS = I->getOperand(2);
2111 unsigned RHSReg = getRegForValue(RHS);
2112 bool RHSIsKill = hasTrivialKill(RHS);
2114 unsigned LHSReg = getRegForValue(LHS);
2115 bool LHSIsKill = hasTrivialKill(LHS);
2117 if (!LHSReg || !RHSReg)
2120 const TargetRegisterInfo &TRI = *Subtarget->getRegisterInfo();
2121 unsigned Opc = X86::getCMovFromCond(CC, TRI.getRegSizeInBits(*RC)/8);
2122 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2124 updateValueMap(I, ResultReg);
2128 /// \brief Emit SSE or AVX instructions to lower the select.
2130 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2131 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
2132 /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
2133 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2134 // Optimize conditions coming from a compare if both instructions are in the
2135 // same basic block (values defined in other basic blocks may not have
2136 // initialized registers).
2137 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2138 if (!CI || (CI->getParent() != I->getParent()))
2141 if (I->getType() != CI->getOperand(0)->getType() ||
2142 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2143 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2146 const Value *CmpLHS = CI->getOperand(0);
2147 const Value *CmpRHS = CI->getOperand(1);
2148 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2150 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2151 // We don't have to materialize a zero constant for this case and can just use
2152 // %x again on the RHS.
2153 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2154 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2155 if (CmpRHSC && CmpRHSC->isNullValue())
2161 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2166 std::swap(CmpLHS, CmpRHS);
2168 // Choose the SSE instruction sequence based on data type (float or double).
2169 static const uint16_t OpcTable[2][4] = {
2170 { X86::CMPSSrr, X86::ANDPSrr, X86::ANDNPSrr, X86::ORPSrr },
2171 { X86::CMPSDrr, X86::ANDPDrr, X86::ANDNPDrr, X86::ORPDrr }
2174 const uint16_t *Opc = nullptr;
2175 switch (RetVT.SimpleTy) {
2176 default: return false;
2177 case MVT::f32: Opc = &OpcTable[0][0]; break;
2178 case MVT::f64: Opc = &OpcTable[1][0]; break;
2181 const Value *LHS = I->getOperand(1);
2182 const Value *RHS = I->getOperand(2);
2184 unsigned LHSReg = getRegForValue(LHS);
2185 bool LHSIsKill = hasTrivialKill(LHS);
2187 unsigned RHSReg = getRegForValue(RHS);
2188 bool RHSIsKill = hasTrivialKill(RHS);
2190 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2191 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2193 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2194 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2196 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2199 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2202 if (Subtarget->hasAVX512()) {
2203 // If we have AVX512 we can use a mask compare and masked movss/sd.
2204 const TargetRegisterClass *VR128X = &X86::VR128XRegClass;
2205 const TargetRegisterClass *VK1 = &X86::VK1RegClass;
2207 unsigned CmpOpcode =
2208 (RetVT == MVT::f32) ? X86::VCMPSSZrr : X86::VCMPSDZrr;
2209 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, VK1, CmpLHSReg, CmpLHSIsKill,
2210 CmpRHSReg, CmpRHSIsKill, CC);
2212 // Need an IMPLICIT_DEF for the input that is used to generate the upper
2213 // bits of the result register since its not based on any of the inputs.
2214 unsigned ImplicitDefReg = createResultReg(VR128X);
2215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2216 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2218 // Place RHSReg is the passthru of the masked movss/sd operation and put
2219 // LHS in the input. The mask input comes from the compare.
2220 unsigned MovOpcode =
2221 (RetVT == MVT::f32) ? X86::VMOVSSZrrk : X86::VMOVSDZrrk;
2222 unsigned MovReg = fastEmitInst_rrrr(MovOpcode, VR128X, RHSReg, RHSIsKill,
2223 CmpReg, true, ImplicitDefReg, true,
2226 ResultReg = createResultReg(RC);
2227 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2228 TII.get(TargetOpcode::COPY), ResultReg).addReg(MovReg);
2230 } else if (Subtarget->hasAVX()) {
2231 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2233 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2234 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2235 // uses XMM0 as the selection register. That may need just as many
2236 // instructions as the AND/ANDN/OR sequence due to register moves, so
2238 unsigned CmpOpcode =
2239 (RetVT == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2240 unsigned BlendOpcode =
2241 (RetVT == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2243 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
2244 CmpRHSReg, CmpRHSIsKill, CC);
2245 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2246 LHSReg, LHSIsKill, CmpReg, true);
2247 ResultReg = createResultReg(RC);
2248 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2249 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
2251 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2252 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2253 CmpRHSReg, CmpRHSIsKill, CC);
2254 unsigned AndReg = fastEmitInst_rr(Opc[1], VR128, CmpReg, /*IsKill=*/false,
2256 unsigned AndNReg = fastEmitInst_rr(Opc[2], VR128, CmpReg, /*IsKill=*/true,
2258 unsigned OrReg = fastEmitInst_rr(Opc[3], VR128, AndNReg, /*IsKill=*/true,
2259 AndReg, /*IsKill=*/true);
2260 ResultReg = createResultReg(RC);
2261 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2262 TII.get(TargetOpcode::COPY), ResultReg).addReg(OrReg);
2264 updateValueMap(I, ResultReg);
2268 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2269 // These are pseudo CMOV instructions and will be later expanded into control-
2272 switch (RetVT.SimpleTy) {
2273 default: return false;
2274 case MVT::i8: Opc = X86::CMOV_GR8; break;
2275 case MVT::i16: Opc = X86::CMOV_GR16; break;
2276 case MVT::i32: Opc = X86::CMOV_GR32; break;
2277 case MVT::f32: Opc = X86::CMOV_FR32; break;
2278 case MVT::f64: Opc = X86::CMOV_FR64; break;
2281 const Value *Cond = I->getOperand(0);
2282 X86::CondCode CC = X86::COND_NE;
2284 // Optimize conditions coming from a compare if both instructions are in the
2285 // same basic block (values defined in other basic blocks may not have
2286 // initialized registers).
2287 const auto *CI = dyn_cast<CmpInst>(Cond);
2288 if (CI && (CI->getParent() == I->getParent())) {
2290 std::tie(CC, NeedSwap) = X86::getX86ConditionCode(CI->getPredicate());
2291 if (CC > X86::LAST_VALID_COND)
2294 const Value *CmpLHS = CI->getOperand(0);
2295 const Value *CmpRHS = CI->getOperand(1);
2298 std::swap(CmpLHS, CmpRHS);
2300 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2301 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2304 unsigned CondReg = getRegForValue(Cond);
2307 bool CondIsKill = hasTrivialKill(Cond);
2309 // In case OpReg is a K register, COPY to a GPR
2310 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2311 unsigned KCondReg = CondReg;
2312 CondReg = createResultReg(&X86::GR32RegClass);
2313 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2314 TII.get(TargetOpcode::COPY), CondReg)
2315 .addReg(KCondReg, getKillRegState(CondIsKill));
2316 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, /*Kill=*/true,
2319 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2320 .addReg(CondReg, getKillRegState(CondIsKill))
2324 const Value *LHS = I->getOperand(1);
2325 const Value *RHS = I->getOperand(2);
2327 unsigned LHSReg = getRegForValue(LHS);
2328 bool LHSIsKill = hasTrivialKill(LHS);
2330 unsigned RHSReg = getRegForValue(RHS);
2331 bool RHSIsKill = hasTrivialKill(RHS);
2333 if (!LHSReg || !RHSReg)
2336 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2338 unsigned ResultReg =
2339 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2340 updateValueMap(I, ResultReg);
2344 bool X86FastISel::X86SelectSelect(const Instruction *I) {
2346 if (!isTypeLegal(I->getType(), RetVT))
2349 // Check if we can fold the select.
2350 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2351 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2352 const Value *Opnd = nullptr;
2353 switch (Predicate) {
2355 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2356 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2358 // No need for a select anymore - this is an unconditional move.
2360 unsigned OpReg = getRegForValue(Opnd);
2363 bool OpIsKill = hasTrivialKill(Opnd);
2364 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2365 unsigned ResultReg = createResultReg(RC);
2366 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2367 TII.get(TargetOpcode::COPY), ResultReg)
2368 .addReg(OpReg, getKillRegState(OpIsKill));
2369 updateValueMap(I, ResultReg);
2374 // First try to use real conditional move instructions.
2375 if (X86FastEmitCMoveSelect(RetVT, I))
2378 // Try to use a sequence of SSE instructions to simulate a conditional move.
2379 if (X86FastEmitSSESelect(RetVT, I))
2382 // Fall-back to pseudo conditional move instructions, which will be later
2383 // converted to control-flow.
2384 if (X86FastEmitPseudoSelect(RetVT, I))
2390 bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2391 // The target-independent selection algorithm in FastISel already knows how
2392 // to select a SINT_TO_FP if the target is SSE but not AVX.
2393 // Early exit if the subtarget doesn't have AVX.
2394 if (!Subtarget->hasAVX())
2397 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2400 // Select integer to float/double conversion.
2401 unsigned OpReg = getRegForValue(I->getOperand(0));
2405 const TargetRegisterClass *RC = nullptr;
2408 if (I->getType()->isDoubleTy()) {
2409 // sitofp int -> double
2410 Opcode = X86::VCVTSI2SDrr;
2411 RC = &X86::FR64RegClass;
2412 } else if (I->getType()->isFloatTy()) {
2413 // sitofp int -> float
2414 Opcode = X86::VCVTSI2SSrr;
2415 RC = &X86::FR32RegClass;
2419 unsigned ImplicitDefReg = createResultReg(RC);
2420 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2421 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2422 unsigned ResultReg =
2423 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2424 updateValueMap(I, ResultReg);
2428 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2429 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2431 const TargetRegisterClass *RC) {
2432 assert((I->getOpcode() == Instruction::FPExt ||
2433 I->getOpcode() == Instruction::FPTrunc) &&
2434 "Instruction must be an FPExt or FPTrunc!");
2436 unsigned OpReg = getRegForValue(I->getOperand(0));
2440 unsigned ImplicitDefReg;
2441 if (Subtarget->hasAVX()) {
2442 ImplicitDefReg = createResultReg(RC);
2443 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2444 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2448 unsigned ResultReg = createResultReg(RC);
2449 MachineInstrBuilder MIB;
2450 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2453 if (Subtarget->hasAVX())
2454 MIB.addReg(ImplicitDefReg);
2457 updateValueMap(I, ResultReg);
2461 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2462 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2463 I->getOperand(0)->getType()->isFloatTy()) {
2464 // fpext from float to double.
2465 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2466 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2472 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2473 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2474 I->getOperand(0)->getType()->isDoubleTy()) {
2475 // fptrunc from double to float.
2476 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2477 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2483 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2484 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2485 EVT DstVT = TLI.getValueType(DL, I->getType());
2487 // This code only handles truncation to byte.
2488 // TODO: Support truncate to i1 with AVX512.
2489 if (DstVT != MVT::i8 && (DstVT != MVT::i1 || Subtarget->hasAVX512()))
2491 if (!TLI.isTypeLegal(SrcVT))
2494 unsigned InputReg = getRegForValue(I->getOperand(0));
2496 // Unhandled operand. Halt "fast" selection and bail.
2499 if (SrcVT == MVT::i8) {
2500 // Truncate from i8 to i1; no code needed.
2501 updateValueMap(I, InputReg);
2505 bool KillInputReg = false;
2506 if (!Subtarget->is64Bit()) {
2507 // If we're on x86-32; we can't extract an i8 from a general register.
2508 // First issue a copy to GR16_ABCD or GR32_ABCD.
2509 const TargetRegisterClass *CopyRC =
2510 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2511 unsigned CopyReg = createResultReg(CopyRC);
2512 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2513 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2515 KillInputReg = true;
2518 // Issue an extract_subreg.
2519 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2520 InputReg, KillInputReg,
2525 updateValueMap(I, ResultReg);
2529 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2530 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2533 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2534 X86AddressMode SrcAM, uint64_t Len) {
2536 // Make sure we don't bloat code by inlining very large memcpy's.
2537 if (!IsMemcpySmall(Len))
2540 bool i64Legal = Subtarget->is64Bit();
2542 // We don't care about alignment here since we just emit integer accesses.
2545 if (Len >= 8 && i64Legal)
2555 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2556 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2557 assert(RV && "Failed to emit load or store??");
2559 unsigned Size = VT.getSizeInBits()/8;
2561 DestAM.Disp += Size;
2568 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2569 // FIXME: Handle more intrinsics.
2570 switch (II->getIntrinsicID()) {
2571 default: return false;
2572 case Intrinsic::convert_from_fp16:
2573 case Intrinsic::convert_to_fp16: {
2574 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
2577 const Value *Op = II->getArgOperand(0);
2578 unsigned InputReg = getRegForValue(Op);
2582 // F16C only allows converting from float to half and from half to float.
2583 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2584 if (IsFloatToHalf) {
2585 if (!Op->getType()->isFloatTy())
2588 if (!II->getType()->isFloatTy())
2592 unsigned ResultReg = 0;
2593 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2594 if (IsFloatToHalf) {
2595 // 'InputReg' is implicitly promoted from register class FR32 to
2596 // register class VR128 by method 'constrainOperandRegClass' which is
2597 // directly called by 'fastEmitInst_ri'.
2598 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2599 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2600 // It's consistent with the other FP instructions, which are usually
2601 // controlled by MXCSR.
2602 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
2604 // Move the lower 32-bits of ResultReg to another register of class GR32.
2605 ResultReg = createResultReg(&X86::GR32RegClass);
2606 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2607 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2608 .addReg(InputReg, RegState::Kill);
2610 // The result value is in the lower 16-bits of ResultReg.
2611 unsigned RegIdx = X86::sub_16bit;
2612 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2614 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2615 // Explicitly sign-extend the input to 32-bit.
2616 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2619 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2620 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2621 InputReg, /*Kill=*/true);
2623 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2625 // The result value is in the lower 32-bits of ResultReg.
2626 // Emit an explicit copy from register class VR128 to register class FR32.
2627 ResultReg = createResultReg(&X86::FR32RegClass);
2628 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2629 TII.get(TargetOpcode::COPY), ResultReg)
2630 .addReg(InputReg, RegState::Kill);
2633 updateValueMap(II, ResultReg);
2636 case Intrinsic::frameaddress: {
2637 MachineFunction *MF = FuncInfo.MF;
2638 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2641 Type *RetTy = II->getCalledFunction()->getReturnType();
2644 if (!isTypeLegal(RetTy, VT))
2648 const TargetRegisterClass *RC = nullptr;
2650 switch (VT.SimpleTy) {
2651 default: llvm_unreachable("Invalid result type for frameaddress.");
2652 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2653 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2656 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2657 // we get the wrong frame register.
2658 MachineFrameInfo &MFI = MF->getFrameInfo();
2659 MFI.setFrameAddressIsTaken(true);
2661 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2662 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2663 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2664 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2665 "Invalid Frame Register!");
2667 // Always make a copy of the frame register to to a vreg first, so that we
2668 // never directly reference the frame register (the TwoAddressInstruction-
2669 // Pass doesn't like that).
2670 unsigned SrcReg = createResultReg(RC);
2671 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2672 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2674 // Now recursively load from the frame address.
2675 // movq (%rbp), %rax
2676 // movq (%rax), %rax
2677 // movq (%rax), %rax
2680 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2682 DestReg = createResultReg(RC);
2683 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2684 TII.get(Opc), DestReg), SrcReg);
2688 updateValueMap(II, SrcReg);
2691 case Intrinsic::memcpy: {
2692 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2693 // Don't handle volatile or variable length memcpys.
2694 if (MCI->isVolatile())
2697 if (isa<ConstantInt>(MCI->getLength())) {
2698 // Small memcpy's are common enough that we want to do them
2699 // without a call if possible.
2700 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2701 if (IsMemcpySmall(Len)) {
2702 X86AddressMode DestAM, SrcAM;
2703 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2704 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2706 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2711 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2712 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2715 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2718 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2720 case Intrinsic::memset: {
2721 const MemSetInst *MSI = cast<MemSetInst>(II);
2723 if (MSI->isVolatile())
2726 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2727 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2730 if (MSI->getDestAddressSpace() > 255)
2733 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2735 case Intrinsic::stackprotector: {
2736 // Emit code to store the stack guard onto the stack.
2737 EVT PtrTy = TLI.getPointerTy(DL);
2739 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2740 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2742 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2744 // Grab the frame index.
2746 if (!X86SelectAddress(Slot, AM)) return false;
2747 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2750 case Intrinsic::dbg_declare: {
2751 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2753 assert(DI->getAddress() && "Null address should be checked earlier!");
2754 if (!X86SelectAddress(DI->getAddress(), AM))
2756 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2757 // FIXME may need to add RegState::Debug to any registers produced,
2758 // although ESP/EBP should be the only ones at the moment.
2759 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2760 "Expected inlined-at fields to agree");
2761 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2763 .addMetadata(DI->getVariable())
2764 .addMetadata(DI->getExpression());
2767 case Intrinsic::trap: {
2768 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2771 case Intrinsic::sqrt: {
2772 if (!Subtarget->hasSSE1())
2775 Type *RetTy = II->getCalledFunction()->getReturnType();
2778 if (!isTypeLegal(RetTy, VT))
2781 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2782 // is not generated by FastISel yet.
2783 // FIXME: Update this code once tablegen can handle it.
2784 static const uint16_t SqrtOpc[2][2] = {
2785 {X86::SQRTSSr, X86::VSQRTSSr},
2786 {X86::SQRTSDr, X86::VSQRTSDr}
2788 bool HasAVX = Subtarget->hasAVX();
2790 const TargetRegisterClass *RC;
2791 switch (VT.SimpleTy) {
2792 default: return false;
2793 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2794 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2797 const Value *SrcVal = II->getArgOperand(0);
2798 unsigned SrcReg = getRegForValue(SrcVal);
2803 unsigned ImplicitDefReg = 0;
2805 ImplicitDefReg = createResultReg(RC);
2806 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2807 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2810 unsigned ResultReg = createResultReg(RC);
2811 MachineInstrBuilder MIB;
2812 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2816 MIB.addReg(ImplicitDefReg);
2820 updateValueMap(II, ResultReg);
2823 case Intrinsic::sadd_with_overflow:
2824 case Intrinsic::uadd_with_overflow:
2825 case Intrinsic::ssub_with_overflow:
2826 case Intrinsic::usub_with_overflow:
2827 case Intrinsic::smul_with_overflow:
2828 case Intrinsic::umul_with_overflow: {
2829 // This implements the basic lowering of the xalu with overflow intrinsics
2830 // into add/sub/mul followed by either seto or setb.
2831 const Function *Callee = II->getCalledFunction();
2832 auto *Ty = cast<StructType>(Callee->getReturnType());
2833 Type *RetTy = Ty->getTypeAtIndex(0U);
2834 assert(Ty->getTypeAtIndex(1)->isIntegerTy() &&
2835 Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 &&
2836 "Overflow value expected to be an i1");
2839 if (!isTypeLegal(RetTy, VT))
2842 if (VT < MVT::i8 || VT > MVT::i64)
2845 const Value *LHS = II->getArgOperand(0);
2846 const Value *RHS = II->getArgOperand(1);
2848 // Canonicalize immediate to the RHS.
2849 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2850 isCommutativeIntrinsic(II))
2851 std::swap(LHS, RHS);
2853 bool UseIncDec = false;
2854 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2857 unsigned BaseOpc, CondOpc;
2858 switch (II->getIntrinsicID()) {
2859 default: llvm_unreachable("Unexpected intrinsic!");
2860 case Intrinsic::sadd_with_overflow:
2861 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2862 CondOpc = X86::SETOr;
2864 case Intrinsic::uadd_with_overflow:
2865 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2866 case Intrinsic::ssub_with_overflow:
2867 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2868 CondOpc = X86::SETOr;
2870 case Intrinsic::usub_with_overflow:
2871 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2872 case Intrinsic::smul_with_overflow:
2873 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2874 case Intrinsic::umul_with_overflow:
2875 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2878 unsigned LHSReg = getRegForValue(LHS);
2881 bool LHSIsKill = hasTrivialKill(LHS);
2883 unsigned ResultReg = 0;
2884 // Check if we have an immediate version.
2885 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2886 static const uint16_t Opc[2][4] = {
2887 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2888 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2891 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2892 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2893 bool IsDec = BaseOpc == X86ISD::DEC;
2894 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2895 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2896 .addReg(LHSReg, getKillRegState(LHSIsKill));
2898 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2899 CI->getZExtValue());
2905 RHSReg = getRegForValue(RHS);
2908 RHSIsKill = hasTrivialKill(RHS);
2909 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2913 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2915 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2916 static const uint16_t MULOpc[] =
2917 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2918 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2919 // First copy the first operand into RAX, which is an implicit input to
2920 // the X86::MUL*r instruction.
2921 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2922 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2923 .addReg(LHSReg, getKillRegState(LHSIsKill));
2924 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2925 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2926 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2927 static const uint16_t MULOpc[] =
2928 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2929 if (VT == MVT::i8) {
2930 // Copy the first operand into AL, which is an implicit input to the
2931 // X86::IMUL8r instruction.
2932 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2933 TII.get(TargetOpcode::COPY), X86::AL)
2934 .addReg(LHSReg, getKillRegState(LHSIsKill));
2935 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2938 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2939 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2946 // Assign to a GPR since the overflow return value is lowered to a SETcc.
2947 unsigned ResultReg2 = createResultReg(&X86::GR8RegClass);
2948 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2949 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2952 updateValueMap(II, ResultReg, 2);
2955 case Intrinsic::x86_sse_cvttss2si:
2956 case Intrinsic::x86_sse_cvttss2si64:
2957 case Intrinsic::x86_sse2_cvttsd2si:
2958 case Intrinsic::x86_sse2_cvttsd2si64: {
2960 switch (II->getIntrinsicID()) {
2961 default: llvm_unreachable("Unexpected intrinsic.");
2962 case Intrinsic::x86_sse_cvttss2si:
2963 case Intrinsic::x86_sse_cvttss2si64:
2964 if (!Subtarget->hasSSE1())
2966 IsInputDouble = false;
2968 case Intrinsic::x86_sse2_cvttsd2si:
2969 case Intrinsic::x86_sse2_cvttsd2si64:
2970 if (!Subtarget->hasSSE2())
2972 IsInputDouble = true;
2976 Type *RetTy = II->getCalledFunction()->getReturnType();
2978 if (!isTypeLegal(RetTy, VT))
2981 static const uint16_t CvtOpc[2][2][2] = {
2982 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2983 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2984 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2985 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2987 bool HasAVX = Subtarget->hasAVX();
2989 switch (VT.SimpleTy) {
2990 default: llvm_unreachable("Unexpected result type.");
2991 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2992 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2995 // Check if we can fold insertelement instructions into the convert.
2996 const Value *Op = II->getArgOperand(0);
2997 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2998 const Value *Index = IE->getOperand(2);
2999 if (!isa<ConstantInt>(Index))
3001 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
3004 Op = IE->getOperand(1);
3007 Op = IE->getOperand(0);
3010 unsigned Reg = getRegForValue(Op);
3014 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3015 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3018 updateValueMap(II, ResultReg);
3024 bool X86FastISel::fastLowerArguments() {
3025 if (!FuncInfo.CanLowerReturn)
3028 const Function *F = FuncInfo.Fn;
3032 CallingConv::ID CC = F->getCallingConv();
3033 if (CC != CallingConv::C)
3036 if (Subtarget->isCallingConvWin64(CC))
3039 if (!Subtarget->is64Bit())
3042 if (Subtarget->useSoftFloat())
3045 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
3046 unsigned GPRCnt = 0;
3047 unsigned FPRCnt = 0;
3048 for (auto const &Arg : F->args()) {
3049 if (Arg.hasAttribute(Attribute::ByVal) ||
3050 Arg.hasAttribute(Attribute::InReg) ||
3051 Arg.hasAttribute(Attribute::StructRet) ||
3052 Arg.hasAttribute(Attribute::SwiftSelf) ||
3053 Arg.hasAttribute(Attribute::SwiftError) ||
3054 Arg.hasAttribute(Attribute::Nest))
3057 Type *ArgTy = Arg.getType();
3058 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3061 EVT ArgVT = TLI.getValueType(DL, ArgTy);
3062 if (!ArgVT.isSimple()) return false;
3063 switch (ArgVT.getSimpleVT().SimpleTy) {
3064 default: return false;
3071 if (!Subtarget->hasSSE1())
3084 static const MCPhysReg GPR32ArgRegs[] = {
3085 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
3087 static const MCPhysReg GPR64ArgRegs[] = {
3088 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
3090 static const MCPhysReg XMMArgRegs[] = {
3091 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3092 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3095 unsigned GPRIdx = 0;
3096 unsigned FPRIdx = 0;
3097 for (auto const &Arg : F->args()) {
3098 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
3099 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
3101 switch (VT.SimpleTy) {
3102 default: llvm_unreachable("Unexpected value type.");
3103 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
3104 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
3105 case MVT::f32: LLVM_FALLTHROUGH;
3106 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
3108 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3109 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3110 // Without this, EmitLiveInCopies may eliminate the livein if its only
3111 // use is a bitcast (which isn't turned into an instruction).
3112 unsigned ResultReg = createResultReg(RC);
3113 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3114 TII.get(TargetOpcode::COPY), ResultReg)
3115 .addReg(DstReg, getKillRegState(true));
3116 updateValueMap(&Arg, ResultReg);
3121 static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
3123 ImmutableCallSite *CS) {
3124 if (Subtarget->is64Bit())
3126 if (Subtarget->getTargetTriple().isOSMSVCRT())
3128 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3129 CC == CallingConv::HiPE)
3133 if (CS->arg_empty() || !CS->paramHasAttr(0, Attribute::StructRet) ||
3134 CS->paramHasAttr(0, Attribute::InReg) || Subtarget->isTargetMCU())
3140 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3141 auto &OutVals = CLI.OutVals;
3142 auto &OutFlags = CLI.OutFlags;
3143 auto &OutRegs = CLI.OutRegs;
3144 auto &Ins = CLI.Ins;
3145 auto &InRegs = CLI.InRegs;
3146 CallingConv::ID CC = CLI.CallConv;
3147 bool &IsTailCall = CLI.IsTailCall;
3148 bool IsVarArg = CLI.IsVarArg;
3149 const Value *Callee = CLI.Callee;
3150 MCSymbol *Symbol = CLI.Symbol;
3152 bool Is64Bit = Subtarget->is64Bit();
3153 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3155 const CallInst *CI =
3156 CLI.CS ? dyn_cast<CallInst>(CLI.CS->getInstruction()) : nullptr;
3157 const Function *CalledFn = CI ? CI->getCalledFunction() : nullptr;
3159 // Functions with no_caller_saved_registers that need special handling.
3160 if ((CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3161 (CalledFn && CalledFn->hasFnAttribute("no_caller_saved_registers")))
3164 // Handle only C, fastcc, and webkit_js calling conventions for now.
3166 default: return false;
3167 case CallingConv::C:
3168 case CallingConv::Fast:
3169 case CallingConv::WebKit_JS:
3170 case CallingConv::Swift:
3171 case CallingConv::X86_FastCall:
3172 case CallingConv::X86_StdCall:
3173 case CallingConv::X86_ThisCall:
3174 case CallingConv::Win64:
3175 case CallingConv::X86_64_SysV:
3179 // Allow SelectionDAG isel to handle tail calls.
3183 // fastcc with -tailcallopt is intended to provide a guaranteed
3184 // tail call optimization. Fastisel doesn't know how to do that.
3185 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3188 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3189 // x86-32. Special handling for x86-64 is implemented.
3190 if (IsVarArg && IsWin64)
3193 // Don't know about inalloca yet.
3194 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3197 for (auto Flag : CLI.OutFlags)
3198 if (Flag.isSwiftError())
3201 SmallVector<MVT, 16> OutVTs;
3202 SmallVector<unsigned, 16> ArgRegs;
3204 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3205 // instruction. This is safe because it is common to all FastISel supported
3206 // calling conventions on x86.
3207 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3208 Value *&Val = OutVals[i];
3209 ISD::ArgFlagsTy Flags = OutFlags[i];
3210 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3211 if (CI->getBitWidth() < 32) {
3213 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3215 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3219 // Passing bools around ends up doing a trunc to i1 and passing it.
3220 // Codegen this as an argument + "and 1".
3222 auto *TI = dyn_cast<TruncInst>(Val);
3224 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3225 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3227 Value *PrevVal = TI->getOperand(0);
3228 ResultReg = getRegForValue(PrevVal);
3233 if (!isTypeLegal(PrevVal->getType(), VT))
3237 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3239 if (!isTypeLegal(Val->getType(), VT))
3241 ResultReg = getRegForValue(Val);
3247 ArgRegs.push_back(ResultReg);
3248 OutVTs.push_back(VT);
3251 // Analyze operands of the call, assigning locations to each operand.
3252 SmallVector<CCValAssign, 16> ArgLocs;
3253 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3255 // Allocate shadow area for Win64
3257 CCInfo.AllocateStack(32, 8);
3259 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3261 // Get a count of how many bytes are to be pushed on the stack.
3262 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3264 // Issue CALLSEQ_START
3265 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3266 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
3267 .addImm(NumBytes).addImm(0).addImm(0);
3269 // Walk the register/memloc assignments, inserting copies/loads.
3270 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3271 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3272 CCValAssign const &VA = ArgLocs[i];
3273 const Value *ArgVal = OutVals[VA.getValNo()];
3274 MVT ArgVT = OutVTs[VA.getValNo()];
3276 if (ArgVT == MVT::x86mmx)
3279 unsigned ArgReg = ArgRegs[VA.getValNo()];
3281 // Promote the value if needed.
3282 switch (VA.getLocInfo()) {
3283 case CCValAssign::Full: break;
3284 case CCValAssign::SExt: {
3285 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3286 "Unexpected extend");
3288 if (ArgVT == MVT::i1)
3291 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3293 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3294 ArgVT = VA.getLocVT();
3297 case CCValAssign::ZExt: {
3298 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3299 "Unexpected extend");
3301 // Handle zero-extension from i1 to i8, which is common.
3302 if (ArgVT == MVT::i1) {
3303 // In case SrcReg is a K register, COPY to a GPR
3304 if (MRI.getRegClass(ArgReg) == &X86::VK1RegClass) {
3305 unsigned KArgReg = ArgReg;
3306 ArgReg = createResultReg(&X86::GR32RegClass);
3307 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3308 TII.get(TargetOpcode::COPY), ArgReg)
3310 ArgReg = fastEmitInst_extractsubreg(MVT::i8, ArgReg, /*Kill=*/true,
3313 // Set the high bits to zero.
3314 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3321 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3323 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3324 ArgVT = VA.getLocVT();
3327 case CCValAssign::AExt: {
3328 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3329 "Unexpected extend");
3330 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3333 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3336 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3339 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3340 ArgVT = VA.getLocVT();
3343 case CCValAssign::BCvt: {
3344 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3345 /*TODO: Kill=*/false);
3346 assert(ArgReg && "Failed to emit a bitcast!");
3347 ArgVT = VA.getLocVT();
3350 case CCValAssign::VExt:
3351 // VExt has not been implemented, so this should be impossible to reach
3352 // for now. However, fallback to Selection DAG isel once implemented.
3354 case CCValAssign::AExtUpper:
3355 case CCValAssign::SExtUpper:
3356 case CCValAssign::ZExtUpper:
3357 case CCValAssign::FPExt:
3358 llvm_unreachable("Unexpected loc info!");
3359 case CCValAssign::Indirect:
3360 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3365 if (VA.isRegLoc()) {
3366 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3367 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3368 OutRegs.push_back(VA.getLocReg());
3370 assert(VA.isMemLoc());
3372 // Don't emit stores for undef values.
3373 if (isa<UndefValue>(ArgVal))
3376 unsigned LocMemOffset = VA.getLocMemOffset();
3378 AM.Base.Reg = RegInfo->getStackRegister();
3379 AM.Disp = LocMemOffset;
3380 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3381 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3382 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3383 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3384 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3385 if (Flags.isByVal()) {
3386 X86AddressMode SrcAM;
3387 SrcAM.Base.Reg = ArgReg;
3388 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3390 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3391 // If this is a really simple value, emit this with the Value* version
3392 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3393 // as it can cause us to reevaluate the argument.
3394 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3397 bool ValIsKill = hasTrivialKill(ArgVal);
3398 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3404 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3406 if (Subtarget->isPICStyleGOT()) {
3407 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3408 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3409 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3412 if (Is64Bit && IsVarArg && !IsWin64) {
3413 // From AMD64 ABI document:
3414 // For calls that may call functions that use varargs or stdargs
3415 // (prototype-less calls or calls to functions containing ellipsis (...) in
3416 // the declaration) %al is used as hidden argument to specify the number
3417 // of SSE registers used. The contents of %al do not need to match exactly
3418 // the number of registers, but must be an ubound on the number of SSE
3419 // registers used and is in the range 0 - 8 inclusive.
3421 // Count the number of XMM registers allocated.
3422 static const MCPhysReg XMMArgRegs[] = {
3423 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3424 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3426 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3427 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3428 && "SSE registers cannot be used when SSE is disabled");
3429 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3430 X86::AL).addImm(NumXMMRegs);
3433 // Materialize callee address in a register. FIXME: GV address can be
3434 // handled with a CALLpcrel32 instead.
3435 X86AddressMode CalleeAM;
3436 if (!X86SelectCallAddress(Callee, CalleeAM))
3439 unsigned CalleeOp = 0;
3440 const GlobalValue *GV = nullptr;
3441 if (CalleeAM.GV != nullptr) {
3443 } else if (CalleeAM.Base.Reg != 0) {
3444 CalleeOp = CalleeAM.Base.Reg;
3449 MachineInstrBuilder MIB;
3451 // Register-indirect call.
3452 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3453 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3457 assert(GV && "Not a direct call");
3458 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3460 // See if we need any target-specific flags on the GV operand.
3461 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
3462 // Ignore NonLazyBind attribute in FastISel
3463 if (OpFlags == X86II::MO_GOTPCREL)
3466 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3468 MIB.addSym(Symbol, OpFlags);
3470 MIB.addGlobalAddress(GV, 0, OpFlags);
3473 // Add a register mask operand representing the call-preserved registers.
3474 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3475 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3477 // Add an implicit use GOT pointer in EBX.
3478 if (Subtarget->isPICStyleGOT())
3479 MIB.addReg(X86::EBX, RegState::Implicit);
3481 if (Is64Bit && IsVarArg && !IsWin64)
3482 MIB.addReg(X86::AL, RegState::Implicit);
3484 // Add implicit physical register uses to the call.
3485 for (auto Reg : OutRegs)
3486 MIB.addReg(Reg, RegState::Implicit);
3488 // Issue CALLSEQ_END
3489 unsigned NumBytesForCalleeToPop =
3490 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3491 TM.Options.GuaranteedTailCallOpt)
3492 ? NumBytes // Callee pops everything.
3493 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
3494 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3495 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3496 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3498 // Now handle call return values.
3499 SmallVector<CCValAssign, 16> RVLocs;
3500 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3501 CLI.RetTy->getContext());
3502 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3504 // Copy all of the result registers out of their specified physreg.
3505 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3506 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3507 CCValAssign &VA = RVLocs[i];
3508 EVT CopyVT = VA.getValVT();
3509 unsigned CopyReg = ResultReg + i;
3510 unsigned SrcReg = VA.getLocReg();
3512 // If this is x86-64, and we disabled SSE, we can't return FP values
3513 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3514 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3515 report_fatal_error("SSE register return with SSE disabled");
3518 // If the return value is an i1 and AVX-512 is enabled, we need
3519 // to do a fixup to make the copy legal.
3520 if (CopyVT == MVT::i1 && SrcReg == X86::AL && Subtarget->hasAVX512()) {
3521 // Need to copy to a GR32 first.
3522 // TODO: MOVZX isn't great here. We don't care about the upper bits.
3523 SrcReg = createResultReg(&X86::GR32RegClass);
3524 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3525 TII.get(X86::MOVZX32rr8), SrcReg).addReg(X86::AL);
3528 // If we prefer to use the value in xmm registers, copy it out as f80 and
3529 // use a truncate to move it from fp stack reg to xmm reg.
3530 if ((SrcReg == X86::FP0 || SrcReg == X86::FP1) &&
3531 isScalarFPTypeInSSEReg(VA.getValVT())) {
3533 CopyReg = createResultReg(&X86::RFP80RegClass);
3536 // Copy out the result.
3537 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3538 TII.get(TargetOpcode::COPY), CopyReg).addReg(SrcReg);
3539 InRegs.push_back(VA.getLocReg());
3541 // Round the f80 to the right size, which also moves it to the appropriate
3542 // xmm register. This is accomplished by storing the f80 value in memory
3543 // and then loading it back.
3544 if (CopyVT != VA.getValVT()) {
3545 EVT ResVT = VA.getValVT();
3546 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3547 unsigned MemSize = ResVT.getSizeInBits()/8;
3548 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3549 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3552 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3553 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3554 TII.get(Opc), ResultReg + i), FI);
3558 CLI.ResultReg = ResultReg;
3559 CLI.NumResultRegs = RVLocs.size();
3566 X86FastISel::fastSelectInstruction(const Instruction *I) {
3567 switch (I->getOpcode()) {
3569 case Instruction::Load:
3570 return X86SelectLoad(I);
3571 case Instruction::Store:
3572 return X86SelectStore(I);
3573 case Instruction::Ret:
3574 return X86SelectRet(I);
3575 case Instruction::ICmp:
3576 case Instruction::FCmp:
3577 return X86SelectCmp(I);
3578 case Instruction::ZExt:
3579 return X86SelectZExt(I);
3580 case Instruction::Br:
3581 return X86SelectBranch(I);
3582 case Instruction::LShr:
3583 case Instruction::AShr:
3584 case Instruction::Shl:
3585 return X86SelectShift(I);
3586 case Instruction::SDiv:
3587 case Instruction::UDiv:
3588 case Instruction::SRem:
3589 case Instruction::URem:
3590 return X86SelectDivRem(I);
3591 case Instruction::Select:
3592 return X86SelectSelect(I);
3593 case Instruction::Trunc:
3594 return X86SelectTrunc(I);
3595 case Instruction::FPExt:
3596 return X86SelectFPExt(I);
3597 case Instruction::FPTrunc:
3598 return X86SelectFPTrunc(I);
3599 case Instruction::SIToFP:
3600 return X86SelectSIToFP(I);
3601 case Instruction::IntToPtr: // Deliberate fall-through.
3602 case Instruction::PtrToInt: {
3603 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3604 EVT DstVT = TLI.getValueType(DL, I->getType());
3605 if (DstVT.bitsGT(SrcVT))
3606 return X86SelectZExt(I);
3607 if (DstVT.bitsLT(SrcVT))
3608 return X86SelectTrunc(I);
3609 unsigned Reg = getRegForValue(I->getOperand(0));
3610 if (Reg == 0) return false;
3611 updateValueMap(I, Reg);
3614 case Instruction::BitCast: {
3615 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3616 if (!Subtarget->hasSSE2())
3619 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3620 EVT DstVT = TLI.getValueType(DL, I->getType());
3622 if (!SrcVT.isSimple() || !DstVT.isSimple())
3625 MVT SVT = SrcVT.getSimpleVT();
3626 MVT DVT = DstVT.getSimpleVT();
3628 if (!SVT.is128BitVector() &&
3629 !(Subtarget->hasAVX() && SVT.is256BitVector()) &&
3630 !(Subtarget->hasAVX512() && SVT.is512BitVector() &&
3631 (Subtarget->hasBWI() || (SVT.getScalarSizeInBits() >= 32 &&
3632 DVT.getScalarSizeInBits() >= 32))))
3635 unsigned Reg = getRegForValue(I->getOperand(0));
3639 // No instruction is needed for conversion. Reuse the register used by
3640 // the fist operand.
3641 updateValueMap(I, Reg);
3649 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3653 uint64_t Imm = CI->getZExtValue();
3655 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3656 switch (VT.SimpleTy) {
3657 default: llvm_unreachable("Unexpected value type");
3660 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3663 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3668 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3669 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3670 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3671 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3678 switch (VT.SimpleTy) {
3679 default: llvm_unreachable("Unexpected value type");
3681 // TODO: Support this properly.
3682 if (Subtarget->hasAVX512())
3686 case MVT::i8: Opc = X86::MOV8ri; break;
3687 case MVT::i16: Opc = X86::MOV16ri; break;
3688 case MVT::i32: Opc = X86::MOV32ri; break;
3690 if (isUInt<32>(Imm))
3692 else if (isInt<32>(Imm))
3693 Opc = X86::MOV64ri32;
3699 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3700 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3701 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3702 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3703 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3704 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3707 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3710 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3711 if (CFP->isNullValue())
3712 return fastMaterializeFloatZero(CFP);
3714 // Can't handle alternate code models yet.
3715 CodeModel::Model CM = TM.getCodeModel();
3716 if (CM != CodeModel::Small && CM != CodeModel::Large)
3719 // Get opcode and regclass of the output for the given load instruction.
3721 const TargetRegisterClass *RC = nullptr;
3722 switch (VT.SimpleTy) {
3725 if (X86ScalarSSEf32) {
3726 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3727 RC = &X86::FR32RegClass;
3729 Opc = X86::LD_Fp32m;
3730 RC = &X86::RFP32RegClass;
3734 if (X86ScalarSSEf64) {
3735 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3736 RC = &X86::FR64RegClass;
3738 Opc = X86::LD_Fp64m;
3739 RC = &X86::RFP64RegClass;
3743 // No f80 support yet.
3747 // MachineConstantPool wants an explicit alignment.
3748 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3750 // Alignment of vector types. FIXME!
3751 Align = DL.getTypeAllocSize(CFP->getType());
3754 // x86-32 PIC requires a PIC base register for constant pools.
3755 unsigned PICBase = 0;
3756 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3757 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
3758 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3759 else if (OpFlag == X86II::MO_GOTOFF)
3760 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3761 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
3764 // Create the load from the constant pool.
3765 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3766 unsigned ResultReg = createResultReg(RC);
3768 if (CM == CodeModel::Large) {
3769 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3770 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3772 .addConstantPoolIndex(CPI, 0, OpFlag);
3773 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3774 TII.get(Opc), ResultReg);
3775 addDirectMem(MIB, AddrReg);
3776 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3777 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3778 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
3779 MIB->addMemOperand(*FuncInfo.MF, MMO);
3783 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3784 TII.get(Opc), ResultReg),
3785 CPI, PICBase, OpFlag);
3789 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3790 // Can't handle alternate code models yet.
3791 if (TM.getCodeModel() != CodeModel::Small)
3794 // Materialize addresses with LEA/MOV instructions.
3796 if (X86SelectAddress(GV, AM)) {
3797 // If the expression is just a basereg, then we're done, otherwise we need
3799 if (AM.BaseType == X86AddressMode::RegBase &&
3800 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3803 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3804 if (TM.getRelocationModel() == Reloc::Static &&
3805 TLI.getPointerTy(DL) == MVT::i64) {
3806 // The displacement code could be more than 32 bits away so we need to use
3807 // an instruction with a 64 bit immediate
3808 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3810 .addGlobalAddress(GV);
3813 TLI.getPointerTy(DL) == MVT::i32
3814 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3816 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3817 TII.get(Opc), ResultReg), AM);
3824 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3825 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
3827 // Only handle simple types.
3828 if (!CEVT.isSimple())
3830 MVT VT = CEVT.getSimpleVT();
3832 if (const auto *CI = dyn_cast<ConstantInt>(C))
3833 return X86MaterializeInt(CI, VT);
3834 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3835 return X86MaterializeFP(CFP, VT);
3836 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3837 return X86MaterializeGV(GV, VT);
3842 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3843 // Fail on dynamic allocas. At this point, getRegForValue has already
3844 // checked its CSE maps, so if we're here trying to handle a dynamic
3845 // alloca, we're not going to succeed. X86SelectAddress has a
3846 // check for dynamic allocas, because it's called directly from
3847 // various places, but targetMaterializeAlloca also needs a check
3848 // in order to avoid recursion between getRegForValue,
3849 // X86SelectAddrss, and targetMaterializeAlloca.
3850 if (!FuncInfo.StaticAllocaMap.count(C))
3852 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3855 if (!X86SelectAddress(C, AM))
3858 TLI.getPointerTy(DL) == MVT::i32
3859 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3861 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
3862 unsigned ResultReg = createResultReg(RC);
3863 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3864 TII.get(Opc), ResultReg), AM);
3868 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3870 if (!isTypeLegal(CF->getType(), VT))
3873 // Get opcode and regclass for the given zero.
3875 const TargetRegisterClass *RC = nullptr;
3876 switch (VT.SimpleTy) {
3879 if (X86ScalarSSEf32) {
3880 Opc = X86::FsFLD0SS;
3881 RC = &X86::FR32RegClass;
3883 Opc = X86::LD_Fp032;
3884 RC = &X86::RFP32RegClass;
3888 if (X86ScalarSSEf64) {
3889 Opc = X86::FsFLD0SD;
3890 RC = &X86::FR64RegClass;
3892 Opc = X86::LD_Fp064;
3893 RC = &X86::RFP64RegClass;
3897 // No f80 support yet.
3901 unsigned ResultReg = createResultReg(RC);
3902 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3907 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3908 const LoadInst *LI) {
3909 const Value *Ptr = LI->getPointerOperand();
3911 if (!X86SelectAddress(Ptr, AM))
3914 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3916 unsigned Size = DL.getTypeAllocSize(LI->getType());
3917 unsigned Alignment = LI->getAlignment();
3919 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3920 Alignment = DL.getABITypeAlignment(LI->getType());
3922 SmallVector<MachineOperand, 8> AddrOps;
3923 AM.getFullAddress(AddrOps);
3925 MachineInstr *Result = XII.foldMemoryOperandImpl(
3926 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3927 /*AllowCommute=*/true);
3931 // The index register could be in the wrong register class. Unfortunately,
3932 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3933 // to just look at OpNo + the offset to the index reg. We actually need to
3934 // scan the instruction to find the index reg and see if its the correct reg
3936 unsigned OperandNo = 0;
3937 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3938 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3939 MachineOperand &MO = *I;
3940 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
3942 // Found the index reg, now try to rewrite it.
3943 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
3944 MO.getReg(), OperandNo);
3945 if (IndexReg == MO.getReg())
3947 MO.setReg(IndexReg);
3950 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3951 MI->eraseFromParent();
3955 unsigned X86FastISel::fastEmitInst_rrrr(unsigned MachineInstOpcode,
3956 const TargetRegisterClass *RC,
3957 unsigned Op0, bool Op0IsKill,
3958 unsigned Op1, bool Op1IsKill,
3959 unsigned Op2, bool Op2IsKill,
3960 unsigned Op3, bool Op3IsKill) {
3961 const MCInstrDesc &II = TII.get(MachineInstOpcode);
3963 unsigned ResultReg = createResultReg(RC);
3964 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
3965 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
3966 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
3967 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 3);
3969 if (II.getNumDefs() >= 1)
3970 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
3971 .addReg(Op0, getKillRegState(Op0IsKill))
3972 .addReg(Op1, getKillRegState(Op1IsKill))
3973 .addReg(Op2, getKillRegState(Op2IsKill))
3974 .addReg(Op3, getKillRegState(Op3IsKill));
3976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
3977 .addReg(Op0, getKillRegState(Op0IsKill))
3978 .addReg(Op1, getKillRegState(Op1IsKill))
3979 .addReg(Op2, getKillRegState(Op2IsKill))
3980 .addReg(Op3, getKillRegState(Op3IsKill));
3981 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3982 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
3989 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3990 const TargetLibraryInfo *libInfo) {
3991 return new X86FastISel(funcInfo, libInfo);