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/Analysis.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/IR/CallSite.h"
32 #include "llvm/IR/CallingConv.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/Support/ErrorHandling.h"
42 #include "llvm/Target/TargetOptions.h"
47 class X86FastISel final : public FastISel {
48 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
49 /// make the right decision when generating code for different targets.
50 const X86Subtarget *Subtarget;
52 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
53 /// floating point ops.
54 /// When SSE is available, use it for f32 operations.
55 /// When SSE2 is available, use it for f64 operations.
60 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
61 const TargetLibraryInfo *libInfo)
62 : FastISel(funcInfo, libInfo) {
63 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
64 X86ScalarSSEf64 = Subtarget->hasSSE2();
65 X86ScalarSSEf32 = Subtarget->hasSSE1();
68 bool fastSelectInstruction(const Instruction *I) override;
70 /// \brief The specified machine instr operand is a vreg, and that
71 /// vreg is being provided by the specified load instruction. If possible,
72 /// try to fold the load as an operand to the instruction, returning true if
74 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
75 const LoadInst *LI) override;
77 bool fastLowerArguments() override;
78 bool fastLowerCall(CallLoweringInfo &CLI) override;
79 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
81 #include "X86GenFastISel.inc"
84 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT, DebugLoc DL);
86 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO,
89 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
90 MachineMemOperand *MMO = nullptr, bool Aligned = false);
91 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
92 const X86AddressMode &AM,
93 MachineMemOperand *MMO = nullptr, bool Aligned = false);
95 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
98 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
99 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
101 bool X86SelectLoad(const Instruction *I);
103 bool X86SelectStore(const Instruction *I);
105 bool X86SelectRet(const Instruction *I);
107 bool X86SelectCmp(const Instruction *I);
109 bool X86SelectZExt(const Instruction *I);
111 bool X86SelectBranch(const Instruction *I);
113 bool X86SelectShift(const Instruction *I);
115 bool X86SelectDivRem(const Instruction *I);
117 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
119 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
121 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
123 bool X86SelectSelect(const Instruction *I);
125 bool X86SelectTrunc(const Instruction *I);
127 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
128 const TargetRegisterClass *RC);
130 bool X86SelectFPExt(const Instruction *I);
131 bool X86SelectFPTrunc(const Instruction *I);
133 const X86InstrInfo *getInstrInfo() const {
134 return Subtarget->getInstrInfo();
136 const X86TargetMachine *getTargetMachine() const {
137 return static_cast<const X86TargetMachine *>(&TM);
140 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
142 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
143 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
144 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
145 unsigned fastMaterializeConstant(const Constant *C) override;
147 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
149 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
151 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
152 /// computed in an SSE register, not on the X87 floating point stack.
153 bool isScalarFPTypeInSSEReg(EVT VT) const {
154 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
155 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
158 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
160 bool IsMemcpySmall(uint64_t Len);
162 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
163 X86AddressMode SrcAM, uint64_t Len);
165 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
169 } // end anonymous namespace.
171 static std::pair<X86::CondCode, bool>
172 getX86ConditionCode(CmpInst::Predicate Predicate) {
173 X86::CondCode CC = X86::COND_INVALID;
174 bool NeedSwap = false;
177 // Floating-point Predicates
178 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
179 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
180 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
181 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
182 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
183 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
184 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
185 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
186 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
187 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
188 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
189 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
190 case CmpInst::FCMP_OEQ: // fall-through
191 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
193 // Integer Predicates
194 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
195 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
196 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
197 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
198 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
199 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
200 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
201 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
202 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
203 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
206 return std::make_pair(CC, NeedSwap);
209 static std::pair<unsigned, bool>
210 getX86SSEConditionCode(CmpInst::Predicate Predicate) {
212 bool NeedSwap = false;
214 // SSE Condition code mapping:
224 default: llvm_unreachable("Unexpected predicate");
225 case CmpInst::FCMP_OEQ: CC = 0; break;
226 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
227 case CmpInst::FCMP_OLT: CC = 1; break;
228 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
229 case CmpInst::FCMP_OLE: CC = 2; break;
230 case CmpInst::FCMP_UNO: CC = 3; break;
231 case CmpInst::FCMP_UNE: CC = 4; break;
232 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
233 case CmpInst::FCMP_UGE: CC = 5; break;
234 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
235 case CmpInst::FCMP_UGT: CC = 6; break;
236 case CmpInst::FCMP_ORD: CC = 7; break;
237 case CmpInst::FCMP_UEQ:
238 case CmpInst::FCMP_ONE: CC = 8; break;
241 return std::make_pair(CC, NeedSwap);
244 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
245 /// into the user. The condition code will only be updated on success.
246 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
248 if (!isa<ExtractValueInst>(Cond))
251 const auto *EV = cast<ExtractValueInst>(Cond);
252 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
255 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
257 const Function *Callee = II->getCalledFunction();
259 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
260 if (!isTypeLegal(RetTy, RetVT))
263 if (RetVT != MVT::i32 && RetVT != MVT::i64)
267 switch (II->getIntrinsicID()) {
268 default: return false;
269 case Intrinsic::sadd_with_overflow:
270 case Intrinsic::ssub_with_overflow:
271 case Intrinsic::smul_with_overflow:
272 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
273 case Intrinsic::uadd_with_overflow:
274 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
277 // Check if both instructions are in the same basic block.
278 if (II->getParent() != I->getParent())
281 // Make sure nothing is in the way
282 BasicBlock::const_iterator Start = I;
283 BasicBlock::const_iterator End = II;
284 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
285 // We only expect extractvalue instructions between the intrinsic and the
286 // instruction to be selected.
287 if (!isa<ExtractValueInst>(Itr))
290 // Check that the extractvalue operand comes from the intrinsic.
291 const auto *EVI = cast<ExtractValueInst>(Itr);
292 if (EVI->getAggregateOperand() != II)
300 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
301 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
302 if (evt == MVT::Other || !evt.isSimple())
303 // Unhandled type. Halt "fast" selection and bail.
306 VT = evt.getSimpleVT();
307 // For now, require SSE/SSE2 for performing floating-point operations,
308 // since x87 requires additional work.
309 if (VT == MVT::f64 && !X86ScalarSSEf64)
311 if (VT == MVT::f32 && !X86ScalarSSEf32)
313 // Similarly, no f80 support yet.
316 // We only handle legal types. For example, on x86-32 the instruction
317 // selector contains all of the 64-bit instructions from x86-64,
318 // under the assumption that i64 won't be used if the target doesn't
320 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
323 #include "X86GenCallingConv.inc"
325 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
326 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
327 /// Return true and the result register by reference if it is possible.
328 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
329 MachineMemOperand *MMO, unsigned &ResultReg) {
330 // Get opcode and regclass of the output for the given load instruction.
332 const TargetRegisterClass *RC = nullptr;
333 switch (VT.getSimpleVT().SimpleTy) {
334 default: return false;
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 = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
356 RC = &X86::FR32RegClass;
359 RC = &X86::RFP32RegClass;
363 if (X86ScalarSSEf64) {
364 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
365 RC = &X86::FR64RegClass;
368 RC = &X86::RFP64RegClass;
372 // No f80 support yet.
376 ResultReg = createResultReg(RC);
377 MachineInstrBuilder MIB =
378 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
379 addFullAddress(MIB, AM);
381 MIB->addMemOperand(*FuncInfo.MF, MMO);
385 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
386 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
387 /// and a displacement offset, or a GlobalAddress,
388 /// i.e. V. Return true if it is possible.
389 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
390 const X86AddressMode &AM,
391 MachineMemOperand *MMO, bool Aligned) {
392 // Get opcode and regclass of the output for the given store instruction.
394 switch (VT.getSimpleVT().SimpleTy) {
395 case MVT::f80: // No f80 support yet.
396 default: return false;
398 // Mask out all but lowest bit.
399 unsigned AndResult = createResultReg(&X86::GR8RegClass);
400 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
401 TII.get(X86::AND8ri), AndResult)
402 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
405 // FALLTHROUGH, handling i1 as i8.
406 case MVT::i8: Opc = X86::MOV8mr; break;
407 case MVT::i16: Opc = X86::MOV16mr; break;
408 case MVT::i32: Opc = X86::MOV32mr; break;
409 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
411 Opc = X86ScalarSSEf32 ?
412 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
415 Opc = X86ScalarSSEf64 ?
416 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
420 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
422 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
426 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
428 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
435 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
437 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
441 MachineInstrBuilder MIB =
442 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
443 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
445 MIB->addMemOperand(*FuncInfo.MF, MMO);
450 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
451 const X86AddressMode &AM,
452 MachineMemOperand *MMO, bool Aligned) {
453 // Handle 'null' like i32/i64 0.
454 if (isa<ConstantPointerNull>(Val))
455 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
457 // If this is a store of a simple constant, fold the constant into the store.
458 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
461 switch (VT.getSimpleVT().SimpleTy) {
463 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
464 case MVT::i8: Opc = X86::MOV8mi; break;
465 case MVT::i16: Opc = X86::MOV16mi; break;
466 case MVT::i32: Opc = X86::MOV32mi; break;
468 // Must be a 32-bit sign extended value.
469 if (isInt<32>(CI->getSExtValue()))
470 Opc = X86::MOV64mi32;
475 MachineInstrBuilder MIB =
476 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
477 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
478 : CI->getZExtValue());
480 MIB->addMemOperand(*FuncInfo.MF, MMO);
485 unsigned ValReg = getRegForValue(Val);
489 bool ValKill = hasTrivialKill(Val);
490 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
493 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
494 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
495 /// ISD::SIGN_EXTEND).
496 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
497 unsigned Src, EVT SrcVT,
498 unsigned &ResultReg) {
499 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
500 Src, /*TODO: Kill=*/false);
508 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
509 // Handle constant address.
510 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
511 // Can't handle alternate code models yet.
512 if (TM.getCodeModel() != CodeModel::Small)
515 // Can't handle TLS yet.
516 if (GV->isThreadLocal())
519 // RIP-relative addresses can't have additional register operands, so if
520 // we've already folded stuff into the addressing mode, just force the
521 // global value into its own register, which we can use as the basereg.
522 if (!Subtarget->isPICStyleRIPRel() ||
523 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
524 // Okay, we've committed to selecting this global. Set up the address.
527 // Allow the subtarget to classify the global.
528 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
530 // If this reference is relative to the pic base, set it now.
531 if (isGlobalRelativeToPICBase(GVFlags)) {
532 // FIXME: How do we know Base.Reg is free??
533 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
536 // Unless the ABI requires an extra load, return a direct reference to
538 if (!isGlobalStubReference(GVFlags)) {
539 if (Subtarget->isPICStyleRIPRel()) {
540 // Use rip-relative addressing if we can. Above we verified that the
541 // base and index registers are unused.
542 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
543 AM.Base.Reg = X86::RIP;
545 AM.GVOpFlags = GVFlags;
549 // Ok, we need to do a load from a stub. If we've already loaded from
550 // this stub, reuse the loaded pointer, otherwise emit the load now.
551 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
553 if (I != LocalValueMap.end() && I->second != 0) {
556 // Issue load from stub.
558 const TargetRegisterClass *RC = nullptr;
559 X86AddressMode StubAM;
560 StubAM.Base.Reg = AM.Base.Reg;
562 StubAM.GVOpFlags = GVFlags;
564 // Prepare for inserting code in the local-value area.
565 SavePoint SaveInsertPt = enterLocalValueArea();
567 if (TLI.getPointerTy() == MVT::i64) {
569 RC = &X86::GR64RegClass;
571 if (Subtarget->isPICStyleRIPRel())
572 StubAM.Base.Reg = X86::RIP;
575 RC = &X86::GR32RegClass;
578 LoadReg = createResultReg(RC);
579 MachineInstrBuilder LoadMI =
580 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
581 addFullAddress(LoadMI, StubAM);
583 // Ok, back to normal mode.
584 leaveLocalValueArea(SaveInsertPt);
586 // Prevent loading GV stub multiple times in same MBB.
587 LocalValueMap[V] = LoadReg;
590 // Now construct the final address. Note that the Disp, Scale,
591 // and Index values may already be set here.
592 AM.Base.Reg = LoadReg;
598 // If all else fails, try to materialize the value in a register.
599 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
600 if (AM.Base.Reg == 0) {
601 AM.Base.Reg = getRegForValue(V);
602 return AM.Base.Reg != 0;
604 if (AM.IndexReg == 0) {
605 assert(AM.Scale == 1 && "Scale with no index!");
606 AM.IndexReg = getRegForValue(V);
607 return AM.IndexReg != 0;
614 /// X86SelectAddress - Attempt to fill in an address from the given value.
616 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
617 SmallVector<const Value *, 32> GEPs;
619 const User *U = nullptr;
620 unsigned Opcode = Instruction::UserOp1;
621 if (const Instruction *I = dyn_cast<Instruction>(V)) {
622 // Don't walk into other basic blocks; it's possible we haven't
623 // visited them yet, so the instructions may not yet be assigned
624 // virtual registers.
625 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
626 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
627 Opcode = I->getOpcode();
630 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
631 Opcode = C->getOpcode();
635 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
636 if (Ty->getAddressSpace() > 255)
637 // Fast instruction selection doesn't support the special
643 case Instruction::BitCast:
644 // Look past bitcasts.
645 return X86SelectAddress(U->getOperand(0), AM);
647 case Instruction::IntToPtr:
648 // Look past no-op inttoptrs.
649 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
650 return X86SelectAddress(U->getOperand(0), AM);
653 case Instruction::PtrToInt:
654 // Look past no-op ptrtoints.
655 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
656 return X86SelectAddress(U->getOperand(0), AM);
659 case Instruction::Alloca: {
660 // Do static allocas.
661 const AllocaInst *A = cast<AllocaInst>(V);
662 DenseMap<const AllocaInst *, int>::iterator SI =
663 FuncInfo.StaticAllocaMap.find(A);
664 if (SI != FuncInfo.StaticAllocaMap.end()) {
665 AM.BaseType = X86AddressMode::FrameIndexBase;
666 AM.Base.FrameIndex = SI->second;
672 case Instruction::Add: {
673 // Adds of constants are common and easy enough.
674 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
675 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
676 // They have to fit in the 32-bit signed displacement field though.
677 if (isInt<32>(Disp)) {
678 AM.Disp = (uint32_t)Disp;
679 return X86SelectAddress(U->getOperand(0), AM);
685 case Instruction::GetElementPtr: {
686 X86AddressMode SavedAM = AM;
688 // Pattern-match simple GEPs.
689 uint64_t Disp = (int32_t)AM.Disp;
690 unsigned IndexReg = AM.IndexReg;
691 unsigned Scale = AM.Scale;
692 gep_type_iterator GTI = gep_type_begin(U);
693 // Iterate through the indices, folding what we can. Constants can be
694 // folded, and one dynamic index can be handled, if the scale is supported.
695 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
696 i != e; ++i, ++GTI) {
697 const Value *Op = *i;
698 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
699 const StructLayout *SL = DL.getStructLayout(STy);
700 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
704 // A array/variable index is always of the form i*S where S is the
705 // constant scale size. See if we can push the scale into immediates.
706 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
708 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
709 // Constant-offset addressing.
710 Disp += CI->getSExtValue() * S;
713 if (canFoldAddIntoGEP(U, Op)) {
714 // A compatible add with a constant operand. Fold the constant.
716 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
717 Disp += CI->getSExtValue() * S;
718 // Iterate on the other operand.
719 Op = cast<AddOperator>(Op)->getOperand(0);
723 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
724 (S == 1 || S == 2 || S == 4 || S == 8)) {
725 // Scaled-index addressing.
727 IndexReg = getRegForGEPIndex(Op).first;
733 goto unsupported_gep;
737 // Check for displacement overflow.
738 if (!isInt<32>(Disp))
741 AM.IndexReg = IndexReg;
743 AM.Disp = (uint32_t)Disp;
746 if (const GetElementPtrInst *GEP =
747 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
748 // Ok, the GEP indices were covered by constant-offset and scaled-index
749 // addressing. Update the address state and move on to examining the base.
752 } else if (X86SelectAddress(U->getOperand(0), AM)) {
756 // If we couldn't merge the gep value into this addr mode, revert back to
757 // our address and just match the value instead of completely failing.
760 for (SmallVectorImpl<const Value *>::reverse_iterator
761 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
762 if (handleConstantAddresses(*I, AM))
767 // Ok, the GEP indices weren't all covered.
772 return handleConstantAddresses(V, AM);
775 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
777 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
778 const User *U = nullptr;
779 unsigned Opcode = Instruction::UserOp1;
780 const Instruction *I = dyn_cast<Instruction>(V);
781 // Record if the value is defined in the same basic block.
783 // This information is crucial to know whether or not folding an
785 // Indeed, FastISel generates or reuses a virtual register for all
786 // operands of all instructions it selects. Obviously, the definition and
787 // its uses must use the same virtual register otherwise the produced
788 // code is incorrect.
789 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
790 // registers for values that are alive across basic blocks. This ensures
791 // that the values are consistently set between across basic block, even
792 // if different instruction selection mechanisms are used (e.g., a mix of
793 // SDISel and FastISel).
794 // For values local to a basic block, the instruction selection process
795 // generates these virtual registers with whatever method is appropriate
796 // for its needs. In particular, FastISel and SDISel do not share the way
797 // local virtual registers are set.
798 // Therefore, this is impossible (or at least unsafe) to share values
799 // between basic blocks unless they use the same instruction selection
800 // method, which is not guarantee for X86.
801 // Moreover, things like hasOneUse could not be used accurately, if we
802 // allow to reference values across basic blocks whereas they are not
803 // alive across basic blocks initially.
806 Opcode = I->getOpcode();
808 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
809 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
810 Opcode = C->getOpcode();
816 case Instruction::BitCast:
817 // Look past bitcasts if its operand is in the same BB.
819 return X86SelectCallAddress(U->getOperand(0), AM);
822 case Instruction::IntToPtr:
823 // Look past no-op inttoptrs if its operand is in the same BB.
825 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
826 return X86SelectCallAddress(U->getOperand(0), AM);
829 case Instruction::PtrToInt:
830 // Look past no-op ptrtoints if its operand is in the same BB.
832 TLI.getValueType(U->getType()) == TLI.getPointerTy())
833 return X86SelectCallAddress(U->getOperand(0), AM);
837 // Handle constant address.
838 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
839 // Can't handle alternate code models yet.
840 if (TM.getCodeModel() != CodeModel::Small)
843 // RIP-relative addresses can't have additional register operands.
844 if (Subtarget->isPICStyleRIPRel() &&
845 (AM.Base.Reg != 0 || AM.IndexReg != 0))
848 // Can't handle DLL Import.
849 if (GV->hasDLLImportStorageClass())
853 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
854 if (GVar->isThreadLocal())
857 // Okay, we've committed to selecting this global. Set up the basic address.
860 // No ABI requires an extra load for anything other than DLLImport, which
861 // we rejected above. Return a direct reference to the global.
862 if (Subtarget->isPICStyleRIPRel()) {
863 // Use rip-relative addressing if we can. Above we verified that the
864 // base and index registers are unused.
865 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
866 AM.Base.Reg = X86::RIP;
867 } else if (Subtarget->isPICStyleStubPIC()) {
868 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
869 } else if (Subtarget->isPICStyleGOT()) {
870 AM.GVOpFlags = X86II::MO_GOTOFF;
876 // If all else fails, try to materialize the value in a register.
877 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
878 if (AM.Base.Reg == 0) {
879 AM.Base.Reg = getRegForValue(V);
880 return AM.Base.Reg != 0;
882 if (AM.IndexReg == 0) {
883 assert(AM.Scale == 1 && "Scale with no index!");
884 AM.IndexReg = getRegForValue(V);
885 return AM.IndexReg != 0;
893 /// X86SelectStore - Select and emit code to implement store instructions.
894 bool X86FastISel::X86SelectStore(const Instruction *I) {
895 // Atomic stores need special handling.
896 const StoreInst *S = cast<StoreInst>(I);
901 const Value *Val = S->getValueOperand();
902 const Value *Ptr = S->getPointerOperand();
905 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
908 unsigned Alignment = S->getAlignment();
909 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
910 if (Alignment == 0) // Ensure that codegen never sees alignment 0
911 Alignment = ABIAlignment;
912 bool Aligned = Alignment >= ABIAlignment;
915 if (!X86SelectAddress(Ptr, AM))
918 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
921 /// X86SelectRet - Select and emit code to implement ret instructions.
922 bool X86FastISel::X86SelectRet(const Instruction *I) {
923 const ReturnInst *Ret = cast<ReturnInst>(I);
924 const Function &F = *I->getParent()->getParent();
925 const X86MachineFunctionInfo *X86MFInfo =
926 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
928 if (!FuncInfo.CanLowerReturn)
931 CallingConv::ID CC = F.getCallingConv();
932 if (CC != CallingConv::C &&
933 CC != CallingConv::Fast &&
934 CC != CallingConv::X86_FastCall &&
935 CC != CallingConv::X86_64_SysV)
938 if (Subtarget->isCallingConvWin64(CC))
941 // Don't handle popping bytes on return for now.
942 if (X86MFInfo->getBytesToPopOnReturn() != 0)
945 // fastcc with -tailcallopt is intended to provide a guaranteed
946 // tail call optimization. Fastisel doesn't know how to do that.
947 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
950 // Let SDISel handle vararg functions.
954 // Build a list of return value registers.
955 SmallVector<unsigned, 4> RetRegs;
957 if (Ret->getNumOperands() > 0) {
958 SmallVector<ISD::OutputArg, 4> Outs;
959 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
961 // Analyze operands of the call, assigning locations to each operand.
962 SmallVector<CCValAssign, 16> ValLocs;
963 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
964 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
966 const Value *RV = Ret->getOperand(0);
967 unsigned Reg = getRegForValue(RV);
971 // Only handle a single return value for now.
972 if (ValLocs.size() != 1)
975 CCValAssign &VA = ValLocs[0];
977 // Don't bother handling odd stuff for now.
978 if (VA.getLocInfo() != CCValAssign::Full)
980 // Only handle register returns for now.
984 // The calling-convention tables for x87 returns don't tell
986 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
989 unsigned SrcReg = Reg + VA.getValNo();
990 EVT SrcVT = TLI.getValueType(RV->getType());
991 EVT DstVT = VA.getValVT();
992 // Special handling for extended integers.
993 if (SrcVT != DstVT) {
994 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
997 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1000 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1002 if (SrcVT == MVT::i1) {
1003 if (Outs[0].Flags.isSExt())
1005 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1008 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1010 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1011 SrcReg, /*TODO: Kill=*/false);
1015 unsigned DstReg = VA.getLocReg();
1016 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1017 // Avoid a cross-class copy. This is very unlikely.
1018 if (!SrcRC->contains(DstReg))
1020 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1021 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1023 // Add register to return instruction.
1024 RetRegs.push_back(VA.getLocReg());
1027 // The x86-64 ABI for returning structs by value requires that we copy
1028 // the sret argument into %rax for the return. We saved the argument into
1029 // a virtual register in the entry block, so now we copy the value out
1030 // and into %rax. We also do the same with %eax for Win32.
1031 if (F.hasStructRetAttr() &&
1032 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1033 unsigned Reg = X86MFInfo->getSRetReturnReg();
1035 "SRetReturnReg should have been set in LowerFormalArguments()!");
1036 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1037 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1038 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1039 RetRegs.push_back(RetReg);
1042 // Now emit the RET.
1043 MachineInstrBuilder MIB =
1044 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1045 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1046 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1047 MIB.addReg(RetRegs[i], RegState::Implicit);
1051 /// X86SelectLoad - Select and emit code to implement load instructions.
1053 bool X86FastISel::X86SelectLoad(const Instruction *I) {
1054 const LoadInst *LI = cast<LoadInst>(I);
1056 // Atomic loads need special handling.
1061 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1064 const Value *Ptr = LI->getPointerOperand();
1067 if (!X86SelectAddress(Ptr, AM))
1070 unsigned ResultReg = 0;
1071 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg))
1074 updateValueMap(I, ResultReg);
1078 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1079 bool HasAVX = Subtarget->hasAVX();
1080 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1081 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1083 switch (VT.getSimpleVT().SimpleTy) {
1085 case MVT::i8: return X86::CMP8rr;
1086 case MVT::i16: return X86::CMP16rr;
1087 case MVT::i32: return X86::CMP32rr;
1088 case MVT::i64: return X86::CMP64rr;
1090 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1092 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1096 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
1097 /// of the comparison, return an opcode that works for the compare (e.g.
1098 /// CMP32ri) otherwise return 0.
1099 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1100 switch (VT.getSimpleVT().SimpleTy) {
1101 // Otherwise, we can't fold the immediate into this comparison.
1103 case MVT::i8: return X86::CMP8ri;
1104 case MVT::i16: return X86::CMP16ri;
1105 case MVT::i32: return X86::CMP32ri;
1107 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1109 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
1110 return X86::CMP64ri32;
1115 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1116 EVT VT, DebugLoc CurDbgLoc) {
1117 unsigned Op0Reg = getRegForValue(Op0);
1118 if (Op0Reg == 0) return false;
1120 // Handle 'null' like i32/i64 0.
1121 if (isa<ConstantPointerNull>(Op1))
1122 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1124 // We have two options: compare with register or immediate. If the RHS of
1125 // the compare is an immediate that we can fold into this compare, use
1126 // CMPri, otherwise use CMPrr.
1127 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1128 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1129 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1131 .addImm(Op1C->getSExtValue());
1136 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1137 if (CompareOpc == 0) return false;
1139 unsigned Op1Reg = getRegForValue(Op1);
1140 if (Op1Reg == 0) return false;
1141 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1148 bool X86FastISel::X86SelectCmp(const Instruction *I) {
1149 const CmpInst *CI = cast<CmpInst>(I);
1152 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1155 // Try to optimize or fold the cmp.
1156 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1157 unsigned ResultReg = 0;
1158 switch (Predicate) {
1160 case CmpInst::FCMP_FALSE: {
1161 ResultReg = createResultReg(&X86::GR32RegClass);
1162 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1164 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1170 case CmpInst::FCMP_TRUE: {
1171 ResultReg = createResultReg(&X86::GR8RegClass);
1172 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1173 ResultReg).addImm(1);
1179 updateValueMap(I, ResultReg);
1183 const Value *LHS = CI->getOperand(0);
1184 const Value *RHS = CI->getOperand(1);
1186 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1187 // We don't have to materialize a zero constant for this case and can just use
1188 // %x again on the RHS.
1189 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1190 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1191 if (RHSC && RHSC->isNullValue())
1195 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1196 static unsigned SETFOpcTable[2][3] = {
1197 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1198 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1200 unsigned *SETFOpc = nullptr;
1201 switch (Predicate) {
1203 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1204 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1207 ResultReg = createResultReg(&X86::GR8RegClass);
1209 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1212 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1213 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1214 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1216 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1218 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1219 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1220 updateValueMap(I, ResultReg);
1226 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1227 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1228 unsigned Opc = X86::getSETFromCond(CC);
1231 std::swap(LHS, RHS);
1233 // Emit a compare of LHS/RHS.
1234 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1238 updateValueMap(I, ResultReg);
1242 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1243 EVT DstVT = TLI.getValueType(I->getType());
1244 if (!TLI.isTypeLegal(DstVT))
1247 unsigned ResultReg = getRegForValue(I->getOperand(0));
1251 // Handle zero-extension from i1 to i8, which is common.
1252 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1253 if (SrcVT.SimpleTy == MVT::i1) {
1254 // Set the high bits to zero.
1255 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1262 if (DstVT == MVT::i64) {
1263 // Handle extension to 64-bits via sub-register shenanigans.
1266 switch (SrcVT.SimpleTy) {
1267 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1268 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1269 case MVT::i32: MovInst = X86::MOV32rr; break;
1270 default: llvm_unreachable("Unexpected zext to i64 source type");
1273 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1277 ResultReg = createResultReg(&X86::GR64RegClass);
1278 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1280 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1281 } else if (DstVT != MVT::i8) {
1282 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1283 ResultReg, /*Kill=*/true);
1288 updateValueMap(I, ResultReg);
1292 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1293 // Unconditional branches are selected by tablegen-generated code.
1294 // Handle a conditional branch.
1295 const BranchInst *BI = cast<BranchInst>(I);
1296 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1297 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1299 // Fold the common case of a conditional branch with a comparison
1300 // in the same block (values defined on other blocks may not have
1301 // initialized registers).
1303 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1304 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1305 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1307 // Try to optimize or fold the cmp.
1308 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1309 switch (Predicate) {
1311 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1312 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1315 const Value *CmpLHS = CI->getOperand(0);
1316 const Value *CmpRHS = CI->getOperand(1);
1318 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1320 // We don't have to materialize a zero constant for this case and can just
1321 // use %x again on the RHS.
1322 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1323 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1324 if (CmpRHSC && CmpRHSC->isNullValue())
1328 // Try to take advantage of fallthrough opportunities.
1329 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1330 std::swap(TrueMBB, FalseMBB);
1331 Predicate = CmpInst::getInversePredicate(Predicate);
1334 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1335 // code check. Instead two branch instructions are required to check all
1336 // the flags. First we change the predicate to a supported condition code,
1337 // which will be the first branch. Later one we will emit the second
1339 bool NeedExtraBranch = false;
1340 switch (Predicate) {
1342 case CmpInst::FCMP_OEQ:
1343 std::swap(TrueMBB, FalseMBB); // fall-through
1344 case CmpInst::FCMP_UNE:
1345 NeedExtraBranch = true;
1346 Predicate = CmpInst::FCMP_ONE;
1352 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1353 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1355 BranchOpc = X86::GetCondBranchFromCond(CC);
1357 std::swap(CmpLHS, CmpRHS);
1359 // Emit a compare of the LHS and RHS, setting the flags.
1360 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1363 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1366 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1368 if (NeedExtraBranch) {
1369 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1373 // Obtain the branch weight and add the TrueBB to the successor list.
1374 uint32_t BranchWeight = 0;
1376 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1377 TrueMBB->getBasicBlock());
1378 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1380 // Emits an unconditional branch to the FalseBB, obtains the branch
1381 // weight, and adds it to the successor list.
1382 fastEmitBranch(FalseMBB, DbgLoc);
1386 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1387 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1388 // typically happen for _Bool and C++ bools.
1390 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1391 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1392 unsigned TestOpc = 0;
1393 switch (SourceVT.SimpleTy) {
1395 case MVT::i8: TestOpc = X86::TEST8ri; break;
1396 case MVT::i16: TestOpc = X86::TEST16ri; break;
1397 case MVT::i32: TestOpc = X86::TEST32ri; break;
1398 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1401 unsigned OpReg = getRegForValue(TI->getOperand(0));
1402 if (OpReg == 0) return false;
1403 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1404 .addReg(OpReg).addImm(1);
1406 unsigned JmpOpc = X86::JNE_1;
1407 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1408 std::swap(TrueMBB, FalseMBB);
1412 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1414 fastEmitBranch(FalseMBB, DbgLoc);
1415 uint32_t BranchWeight = 0;
1417 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1418 TrueMBB->getBasicBlock());
1419 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1423 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1424 // Fake request the condition, otherwise the intrinsic might be completely
1426 unsigned TmpReg = getRegForValue(BI->getCondition());
1430 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1432 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1434 fastEmitBranch(FalseMBB, DbgLoc);
1435 uint32_t BranchWeight = 0;
1437 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1438 TrueMBB->getBasicBlock());
1439 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1443 // Otherwise do a clumsy setcc and re-test it.
1444 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1445 // in an explicit cast, so make sure to handle that correctly.
1446 unsigned OpReg = getRegForValue(BI->getCondition());
1447 if (OpReg == 0) return false;
1449 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1450 .addReg(OpReg).addImm(1);
1451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1453 fastEmitBranch(FalseMBB, DbgLoc);
1454 uint32_t BranchWeight = 0;
1456 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1457 TrueMBB->getBasicBlock());
1458 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1462 bool X86FastISel::X86SelectShift(const Instruction *I) {
1463 unsigned CReg = 0, OpReg = 0;
1464 const TargetRegisterClass *RC = nullptr;
1465 if (I->getType()->isIntegerTy(8)) {
1467 RC = &X86::GR8RegClass;
1468 switch (I->getOpcode()) {
1469 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1470 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1471 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1472 default: return false;
1474 } else if (I->getType()->isIntegerTy(16)) {
1476 RC = &X86::GR16RegClass;
1477 switch (I->getOpcode()) {
1478 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1479 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1480 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1481 default: return false;
1483 } else if (I->getType()->isIntegerTy(32)) {
1485 RC = &X86::GR32RegClass;
1486 switch (I->getOpcode()) {
1487 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1488 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1489 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1490 default: return false;
1492 } else if (I->getType()->isIntegerTy(64)) {
1494 RC = &X86::GR64RegClass;
1495 switch (I->getOpcode()) {
1496 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1497 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1498 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1499 default: return false;
1506 if (!isTypeLegal(I->getType(), VT))
1509 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1510 if (Op0Reg == 0) return false;
1512 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1513 if (Op1Reg == 0) return false;
1514 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1515 CReg).addReg(Op1Reg);
1517 // The shift instruction uses X86::CL. If we defined a super-register
1518 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1519 if (CReg != X86::CL)
1520 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1521 TII.get(TargetOpcode::KILL), X86::CL)
1522 .addReg(CReg, RegState::Kill);
1524 unsigned ResultReg = createResultReg(RC);
1525 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1527 updateValueMap(I, ResultReg);
1531 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1532 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1533 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1534 const static bool S = true; // IsSigned
1535 const static bool U = false; // !IsSigned
1536 const static unsigned Copy = TargetOpcode::COPY;
1537 // For the X86 DIV/IDIV instruction, in most cases the dividend
1538 // (numerator) must be in a specific register pair highreg:lowreg,
1539 // producing the quotient in lowreg and the remainder in highreg.
1540 // For most data types, to set up the instruction, the dividend is
1541 // copied into lowreg, and lowreg is sign-extended or zero-extended
1542 // into highreg. The exception is i8, where the dividend is defined
1543 // as a single register rather than a register pair, and we
1544 // therefore directly sign-extend or zero-extend the dividend into
1545 // lowreg, instead of copying, and ignore the highreg.
1546 const static struct DivRemEntry {
1547 // The following portion depends only on the data type.
1548 const TargetRegisterClass *RC;
1549 unsigned LowInReg; // low part of the register pair
1550 unsigned HighInReg; // high part of the register pair
1551 // The following portion depends on both the data type and the operation.
1552 struct DivRemResult {
1553 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1554 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1555 // highreg, or copying a zero into highreg.
1556 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1557 // zero/sign-extending into lowreg for i8.
1558 unsigned DivRemResultReg; // Register containing the desired result.
1559 bool IsOpSigned; // Whether to use signed or unsigned form.
1560 } ResultTable[NumOps];
1561 } OpTable[NumTypes] = {
1562 { &X86::GR8RegClass, X86::AX, 0, {
1563 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1564 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1565 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1566 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1569 { &X86::GR16RegClass, X86::AX, X86::DX, {
1570 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1571 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1572 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1573 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1576 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1577 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1578 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1579 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1580 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1583 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1584 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1585 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1586 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1587 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1593 if (!isTypeLegal(I->getType(), VT))
1596 unsigned TypeIndex, OpIndex;
1597 switch (VT.SimpleTy) {
1598 default: return false;
1599 case MVT::i8: TypeIndex = 0; break;
1600 case MVT::i16: TypeIndex = 1; break;
1601 case MVT::i32: TypeIndex = 2; break;
1602 case MVT::i64: TypeIndex = 3;
1603 if (!Subtarget->is64Bit())
1608 switch (I->getOpcode()) {
1609 default: llvm_unreachable("Unexpected div/rem opcode");
1610 case Instruction::SDiv: OpIndex = 0; break;
1611 case Instruction::SRem: OpIndex = 1; break;
1612 case Instruction::UDiv: OpIndex = 2; break;
1613 case Instruction::URem: OpIndex = 3; break;
1616 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1617 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1618 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1621 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1625 // Move op0 into low-order input register.
1626 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1627 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1628 // Zero-extend or sign-extend into high-order input register.
1629 if (OpEntry.OpSignExtend) {
1630 if (OpEntry.IsOpSigned)
1631 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1632 TII.get(OpEntry.OpSignExtend));
1634 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1635 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1636 TII.get(X86::MOV32r0), Zero32);
1638 // Copy the zero into the appropriate sub/super/identical physical
1639 // register. Unfortunately the operations needed are not uniform enough
1640 // to fit neatly into the table above.
1641 if (VT.SimpleTy == MVT::i16) {
1642 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1643 TII.get(Copy), TypeEntry.HighInReg)
1644 .addReg(Zero32, 0, X86::sub_16bit);
1645 } else if (VT.SimpleTy == MVT::i32) {
1646 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1647 TII.get(Copy), TypeEntry.HighInReg)
1649 } else if (VT.SimpleTy == MVT::i64) {
1650 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1651 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1652 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1656 // Generate the DIV/IDIV instruction.
1657 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1658 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1659 // For i8 remainder, we can't reference AH directly, as we'll end
1660 // up with bogus copies like %R9B = COPY %AH. Reference AX
1661 // instead to prevent AH references in a REX instruction.
1663 // The current assumption of the fast register allocator is that isel
1664 // won't generate explicit references to the GPR8_NOREX registers. If
1665 // the allocator and/or the backend get enhanced to be more robust in
1666 // that regard, this can be, and should be, removed.
1667 unsigned ResultReg = 0;
1668 if ((I->getOpcode() == Instruction::SRem ||
1669 I->getOpcode() == Instruction::URem) &&
1670 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1671 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1672 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1673 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1674 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1676 // Shift AX right by 8 bits instead of using AH.
1677 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1678 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1680 // Now reference the 8-bit subreg of the result.
1681 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1682 /*Kill=*/true, X86::sub_8bit);
1684 // Copy the result out of the physreg if we haven't already.
1686 ResultReg = createResultReg(TypeEntry.RC);
1687 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1688 .addReg(OpEntry.DivRemResultReg);
1690 updateValueMap(I, ResultReg);
1695 /// \brief Emit a conditional move instruction (if the are supported) to lower
1697 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1698 // Check if the subtarget supports these instructions.
1699 if (!Subtarget->hasCMov())
1702 // FIXME: Add support for i8.
1703 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1706 const Value *Cond = I->getOperand(0);
1707 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1708 bool NeedTest = true;
1709 X86::CondCode CC = X86::COND_NE;
1711 // Optimize conditions coming from a compare if both instructions are in the
1712 // same basic block (values defined in other basic blocks may not have
1713 // initialized registers).
1714 const auto *CI = dyn_cast<CmpInst>(Cond);
1715 if (CI && (CI->getParent() == I->getParent())) {
1716 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1718 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1719 static unsigned SETFOpcTable[2][3] = {
1720 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1721 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1723 unsigned *SETFOpc = nullptr;
1724 switch (Predicate) {
1726 case CmpInst::FCMP_OEQ:
1727 SETFOpc = &SETFOpcTable[0][0];
1728 Predicate = CmpInst::ICMP_NE;
1730 case CmpInst::FCMP_UNE:
1731 SETFOpc = &SETFOpcTable[1][0];
1732 Predicate = CmpInst::ICMP_NE;
1737 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1738 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1740 const Value *CmpLHS = CI->getOperand(0);
1741 const Value *CmpRHS = CI->getOperand(1);
1743 std::swap(CmpLHS, CmpRHS);
1745 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1746 // Emit a compare of the LHS and RHS, setting the flags.
1747 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1751 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1752 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1753 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1755 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1757 auto const &II = TII.get(SETFOpc[2]);
1758 if (II.getNumDefs()) {
1759 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1760 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1761 .addReg(FlagReg2).addReg(FlagReg1);
1763 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1764 .addReg(FlagReg2).addReg(FlagReg1);
1768 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1769 // Fake request the condition, otherwise the intrinsic might be completely
1771 unsigned TmpReg = getRegForValue(Cond);
1779 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1780 // garbage. Indeed, only the less significant bit is supposed to be
1781 // accurate. If we read more than the lsb, we may see non-zero values
1782 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1783 // the select. This is achieved by performing TEST against 1.
1784 unsigned CondReg = getRegForValue(Cond);
1787 bool CondIsKill = hasTrivialKill(Cond);
1789 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1790 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1793 const Value *LHS = I->getOperand(1);
1794 const Value *RHS = I->getOperand(2);
1796 unsigned RHSReg = getRegForValue(RHS);
1797 bool RHSIsKill = hasTrivialKill(RHS);
1799 unsigned LHSReg = getRegForValue(LHS);
1800 bool LHSIsKill = hasTrivialKill(LHS);
1802 if (!LHSReg || !RHSReg)
1805 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1806 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1808 updateValueMap(I, ResultReg);
1812 /// \brief Emit SSE instructions to lower the select.
1814 /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1815 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
1816 /// SSE instructions are available.
1817 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1818 // Optimize conditions coming from a compare if both instructions are in the
1819 // same basic block (values defined in other basic blocks may not have
1820 // initialized registers).
1821 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1822 if (!CI || (CI->getParent() != I->getParent()))
1825 if (I->getType() != CI->getOperand(0)->getType() ||
1826 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1827 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1830 const Value *CmpLHS = CI->getOperand(0);
1831 const Value *CmpRHS = CI->getOperand(1);
1832 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1834 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1835 // We don't have to materialize a zero constant for this case and can just use
1836 // %x again on the RHS.
1837 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1838 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1839 if (CmpRHSC && CmpRHSC->isNullValue())
1845 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1850 std::swap(CmpLHS, CmpRHS);
1852 static unsigned OpcTable[2][2][4] = {
1853 { { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1854 { X86::VCMPSSrr, X86::VFsANDPSrr, X86::VFsANDNPSrr, X86::VFsORPSrr } },
1855 { { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr },
1856 { X86::VCMPSDrr, X86::VFsANDPDrr, X86::VFsANDNPDrr, X86::VFsORPDrr } }
1859 bool HasAVX = Subtarget->hasAVX();
1860 unsigned *Opc = nullptr;
1861 switch (RetVT.SimpleTy) {
1862 default: return false;
1863 case MVT::f32: Opc = &OpcTable[0][HasAVX][0]; break;
1864 case MVT::f64: Opc = &OpcTable[1][HasAVX][0]; break;
1867 const Value *LHS = I->getOperand(1);
1868 const Value *RHS = I->getOperand(2);
1870 unsigned LHSReg = getRegForValue(LHS);
1871 bool LHSIsKill = hasTrivialKill(LHS);
1873 unsigned RHSReg = getRegForValue(RHS);
1874 bool RHSIsKill = hasTrivialKill(RHS);
1876 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1877 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1879 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1880 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1882 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1885 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1886 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1887 CmpRHSReg, CmpRHSIsKill, CC);
1888 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1890 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1892 unsigned ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1893 AndReg, /*IsKill=*/true);
1894 updateValueMap(I, ResultReg);
1898 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1899 // These are pseudo CMOV instructions and will be later expanded into control-
1902 switch (RetVT.SimpleTy) {
1903 default: return false;
1904 case MVT::i8: Opc = X86::CMOV_GR8; break;
1905 case MVT::i16: Opc = X86::CMOV_GR16; break;
1906 case MVT::i32: Opc = X86::CMOV_GR32; break;
1907 case MVT::f32: Opc = X86::CMOV_FR32; break;
1908 case MVT::f64: Opc = X86::CMOV_FR64; break;
1911 const Value *Cond = I->getOperand(0);
1912 X86::CondCode CC = X86::COND_NE;
1914 // Optimize conditions coming from a compare if both instructions are in the
1915 // same basic block (values defined in other basic blocks may not have
1916 // initialized registers).
1917 const auto *CI = dyn_cast<CmpInst>(Cond);
1918 if (CI && (CI->getParent() == I->getParent())) {
1920 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1921 if (CC > X86::LAST_VALID_COND)
1924 const Value *CmpLHS = CI->getOperand(0);
1925 const Value *CmpRHS = CI->getOperand(1);
1928 std::swap(CmpLHS, CmpRHS);
1930 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1931 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1934 unsigned CondReg = getRegForValue(Cond);
1937 bool CondIsKill = hasTrivialKill(Cond);
1938 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1939 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1942 const Value *LHS = I->getOperand(1);
1943 const Value *RHS = I->getOperand(2);
1945 unsigned LHSReg = getRegForValue(LHS);
1946 bool LHSIsKill = hasTrivialKill(LHS);
1948 unsigned RHSReg = getRegForValue(RHS);
1949 bool RHSIsKill = hasTrivialKill(RHS);
1951 if (!LHSReg || !RHSReg)
1954 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1956 unsigned ResultReg =
1957 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
1958 updateValueMap(I, ResultReg);
1962 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1964 if (!isTypeLegal(I->getType(), RetVT))
1967 // Check if we can fold the select.
1968 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
1969 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1970 const Value *Opnd = nullptr;
1971 switch (Predicate) {
1973 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
1974 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
1976 // No need for a select anymore - this is an unconditional move.
1978 unsigned OpReg = getRegForValue(Opnd);
1981 bool OpIsKill = hasTrivialKill(Opnd);
1982 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1983 unsigned ResultReg = createResultReg(RC);
1984 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1985 TII.get(TargetOpcode::COPY), ResultReg)
1986 .addReg(OpReg, getKillRegState(OpIsKill));
1987 updateValueMap(I, ResultReg);
1992 // First try to use real conditional move instructions.
1993 if (X86FastEmitCMoveSelect(RetVT, I))
1996 // Try to use a sequence of SSE instructions to simulate a conditional move.
1997 if (X86FastEmitSSESelect(RetVT, I))
2000 // Fall-back to pseudo conditional move instructions, which will be later
2001 // converted to control-flow.
2002 if (X86FastEmitPseudoSelect(RetVT, I))
2008 // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2009 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2011 const TargetRegisterClass *RC) {
2012 assert((I->getOpcode() == Instruction::FPExt ||
2013 I->getOpcode() == Instruction::FPTrunc) &&
2014 "Instruction must be an FPExt or FPTrunc!");
2016 unsigned OpReg = getRegForValue(I->getOperand(0));
2020 unsigned ResultReg = createResultReg(RC);
2021 MachineInstrBuilder MIB;
2022 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2024 if (Subtarget->hasAVX())
2027 updateValueMap(I, ResultReg);
2031 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2032 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2033 I->getOperand(0)->getType()->isFloatTy()) {
2034 // fpext from float to double.
2035 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2036 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
2042 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2043 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2044 I->getOperand(0)->getType()->isDoubleTy()) {
2045 // fptrunc from double to float.
2046 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2047 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
2053 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2054 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2055 EVT DstVT = TLI.getValueType(I->getType());
2057 // This code only handles truncation to byte.
2058 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2060 if (!TLI.isTypeLegal(SrcVT))
2063 unsigned InputReg = getRegForValue(I->getOperand(0));
2065 // Unhandled operand. Halt "fast" selection and bail.
2068 if (SrcVT == MVT::i8) {
2069 // Truncate from i8 to i1; no code needed.
2070 updateValueMap(I, InputReg);
2074 if (!Subtarget->is64Bit()) {
2075 // If we're on x86-32; we can't extract an i8 from a general register.
2076 // First issue a copy to GR16_ABCD or GR32_ABCD.
2077 const TargetRegisterClass *CopyRC =
2078 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2079 unsigned CopyReg = createResultReg(CopyRC);
2080 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2081 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2085 // Issue an extract_subreg.
2086 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2087 InputReg, /*Kill=*/true,
2092 updateValueMap(I, ResultReg);
2096 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2097 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2100 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2101 X86AddressMode SrcAM, uint64_t Len) {
2103 // Make sure we don't bloat code by inlining very large memcpy's.
2104 if (!IsMemcpySmall(Len))
2107 bool i64Legal = Subtarget->is64Bit();
2109 // We don't care about alignment here since we just emit integer accesses.
2112 if (Len >= 8 && i64Legal)
2122 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2123 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2124 assert(RV && "Failed to emit load or store??");
2126 unsigned Size = VT.getSizeInBits()/8;
2128 DestAM.Disp += Size;
2135 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2136 // FIXME: Handle more intrinsics.
2137 switch (II->getIntrinsicID()) {
2138 default: return false;
2139 case Intrinsic::frameaddress: {
2140 MachineFunction *MF = FuncInfo.MF;
2141 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2144 Type *RetTy = II->getCalledFunction()->getReturnType();
2147 if (!isTypeLegal(RetTy, VT))
2151 const TargetRegisterClass *RC = nullptr;
2153 switch (VT.SimpleTy) {
2154 default: llvm_unreachable("Invalid result type for frameaddress.");
2155 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2156 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2159 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2160 // we get the wrong frame register.
2161 MachineFrameInfo *MFI = MF->getFrameInfo();
2162 MFI->setFrameAddressIsTaken(true);
2164 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2165 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2166 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2167 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2168 "Invalid Frame Register!");
2170 // Always make a copy of the frame register to to a vreg first, so that we
2171 // never directly reference the frame register (the TwoAddressInstruction-
2172 // Pass doesn't like that).
2173 unsigned SrcReg = createResultReg(RC);
2174 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2175 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2177 // Now recursively load from the frame address.
2178 // movq (%rbp), %rax
2179 // movq (%rax), %rax
2180 // movq (%rax), %rax
2183 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2185 DestReg = createResultReg(RC);
2186 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2187 TII.get(Opc), DestReg), SrcReg);
2191 updateValueMap(II, SrcReg);
2194 case Intrinsic::memcpy: {
2195 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2196 // Don't handle volatile or variable length memcpys.
2197 if (MCI->isVolatile())
2200 if (isa<ConstantInt>(MCI->getLength())) {
2201 // Small memcpy's are common enough that we want to do them
2202 // without a call if possible.
2203 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2204 if (IsMemcpySmall(Len)) {
2205 X86AddressMode DestAM, SrcAM;
2206 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2207 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2209 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2214 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2215 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2218 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2221 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2223 case Intrinsic::memset: {
2224 const MemSetInst *MSI = cast<MemSetInst>(II);
2226 if (MSI->isVolatile())
2229 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2230 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2233 if (MSI->getDestAddressSpace() > 255)
2236 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2238 case Intrinsic::stackprotector: {
2239 // Emit code to store the stack guard onto the stack.
2240 EVT PtrTy = TLI.getPointerTy();
2242 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2243 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2245 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2247 // Grab the frame index.
2249 if (!X86SelectAddress(Slot, AM)) return false;
2250 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2253 case Intrinsic::dbg_declare: {
2254 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2256 assert(DI->getAddress() && "Null address should be checked earlier!");
2257 if (!X86SelectAddress(DI->getAddress(), AM))
2259 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2260 // FIXME may need to add RegState::Debug to any registers produced,
2261 // although ESP/EBP should be the only ones at the moment.
2262 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2264 .addMetadata(DI->getVariable())
2265 .addMetadata(DI->getExpression());
2268 case Intrinsic::trap: {
2269 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2272 case Intrinsic::sqrt: {
2273 if (!Subtarget->hasSSE1())
2276 Type *RetTy = II->getCalledFunction()->getReturnType();
2279 if (!isTypeLegal(RetTy, VT))
2282 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2283 // is not generated by FastISel yet.
2284 // FIXME: Update this code once tablegen can handle it.
2285 static const unsigned SqrtOpc[2][2] = {
2286 {X86::SQRTSSr, X86::VSQRTSSr},
2287 {X86::SQRTSDr, X86::VSQRTSDr}
2289 bool HasAVX = Subtarget->hasAVX();
2291 const TargetRegisterClass *RC;
2292 switch (VT.SimpleTy) {
2293 default: return false;
2294 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2295 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2298 const Value *SrcVal = II->getArgOperand(0);
2299 unsigned SrcReg = getRegForValue(SrcVal);
2304 unsigned ImplicitDefReg = 0;
2306 ImplicitDefReg = createResultReg(RC);
2307 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2308 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2311 unsigned ResultReg = createResultReg(RC);
2312 MachineInstrBuilder MIB;
2313 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2317 MIB.addReg(ImplicitDefReg);
2321 updateValueMap(II, ResultReg);
2324 case Intrinsic::sadd_with_overflow:
2325 case Intrinsic::uadd_with_overflow:
2326 case Intrinsic::ssub_with_overflow:
2327 case Intrinsic::usub_with_overflow:
2328 case Intrinsic::smul_with_overflow:
2329 case Intrinsic::umul_with_overflow: {
2330 // This implements the basic lowering of the xalu with overflow intrinsics
2331 // into add/sub/mul followed by either seto or setb.
2332 const Function *Callee = II->getCalledFunction();
2333 auto *Ty = cast<StructType>(Callee->getReturnType());
2334 Type *RetTy = Ty->getTypeAtIndex(0U);
2335 Type *CondTy = Ty->getTypeAtIndex(1);
2338 if (!isTypeLegal(RetTy, VT))
2341 if (VT < MVT::i8 || VT > MVT::i64)
2344 const Value *LHS = II->getArgOperand(0);
2345 const Value *RHS = II->getArgOperand(1);
2347 // Canonicalize immediate to the RHS.
2348 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2349 isCommutativeIntrinsic(II))
2350 std::swap(LHS, RHS);
2352 bool UseIncDec = false;
2353 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2356 unsigned BaseOpc, CondOpc;
2357 switch (II->getIntrinsicID()) {
2358 default: llvm_unreachable("Unexpected intrinsic!");
2359 case Intrinsic::sadd_with_overflow:
2360 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2361 CondOpc = X86::SETOr;
2363 case Intrinsic::uadd_with_overflow:
2364 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2365 case Intrinsic::ssub_with_overflow:
2366 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2367 CondOpc = X86::SETOr;
2369 case Intrinsic::usub_with_overflow:
2370 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2371 case Intrinsic::smul_with_overflow:
2372 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2373 case Intrinsic::umul_with_overflow:
2374 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2377 unsigned LHSReg = getRegForValue(LHS);
2380 bool LHSIsKill = hasTrivialKill(LHS);
2382 unsigned ResultReg = 0;
2383 // Check if we have an immediate version.
2384 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2385 static const unsigned Opc[2][4] = {
2386 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2387 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2390 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2391 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2392 bool IsDec = BaseOpc == X86ISD::DEC;
2393 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2394 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2395 .addReg(LHSReg, getKillRegState(LHSIsKill));
2397 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2398 CI->getZExtValue());
2404 RHSReg = getRegForValue(RHS);
2407 RHSIsKill = hasTrivialKill(RHS);
2408 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2412 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2414 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2415 static const unsigned MULOpc[] =
2416 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2417 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2418 // First copy the first operand into RAX, which is an implicit input to
2419 // the X86::MUL*r instruction.
2420 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2421 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2422 .addReg(LHSReg, getKillRegState(LHSIsKill));
2423 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2424 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2425 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2426 static const unsigned MULOpc[] =
2427 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2428 if (VT == MVT::i8) {
2429 // Copy the first operand into AL, which is an implicit input to the
2430 // X86::IMUL8r instruction.
2431 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2432 TII.get(TargetOpcode::COPY), X86::AL)
2433 .addReg(LHSReg, getKillRegState(LHSIsKill));
2434 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2437 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2438 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2445 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2446 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2450 updateValueMap(II, ResultReg, 2);
2453 case Intrinsic::x86_sse_cvttss2si:
2454 case Intrinsic::x86_sse_cvttss2si64:
2455 case Intrinsic::x86_sse2_cvttsd2si:
2456 case Intrinsic::x86_sse2_cvttsd2si64: {
2458 switch (II->getIntrinsicID()) {
2459 default: llvm_unreachable("Unexpected intrinsic.");
2460 case Intrinsic::x86_sse_cvttss2si:
2461 case Intrinsic::x86_sse_cvttss2si64:
2462 if (!Subtarget->hasSSE1())
2464 IsInputDouble = false;
2466 case Intrinsic::x86_sse2_cvttsd2si:
2467 case Intrinsic::x86_sse2_cvttsd2si64:
2468 if (!Subtarget->hasSSE2())
2470 IsInputDouble = true;
2474 Type *RetTy = II->getCalledFunction()->getReturnType();
2476 if (!isTypeLegal(RetTy, VT))
2479 static const unsigned CvtOpc[2][2][2] = {
2480 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2481 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2482 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2483 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2485 bool HasAVX = Subtarget->hasAVX();
2487 switch (VT.SimpleTy) {
2488 default: llvm_unreachable("Unexpected result type.");
2489 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2490 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2493 // Check if we can fold insertelement instructions into the convert.
2494 const Value *Op = II->getArgOperand(0);
2495 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2496 const Value *Index = IE->getOperand(2);
2497 if (!isa<ConstantInt>(Index))
2499 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2502 Op = IE->getOperand(1);
2505 Op = IE->getOperand(0);
2508 unsigned Reg = getRegForValue(Op);
2512 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2513 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2516 updateValueMap(II, ResultReg);
2522 bool X86FastISel::fastLowerArguments() {
2523 if (!FuncInfo.CanLowerReturn)
2526 const Function *F = FuncInfo.Fn;
2530 CallingConv::ID CC = F->getCallingConv();
2531 if (CC != CallingConv::C)
2534 if (Subtarget->isCallingConvWin64(CC))
2537 if (!Subtarget->is64Bit())
2540 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2541 unsigned GPRCnt = 0;
2542 unsigned FPRCnt = 0;
2544 for (auto const &Arg : F->args()) {
2545 // The first argument is at index 1.
2547 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2548 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2549 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2550 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2553 Type *ArgTy = Arg.getType();
2554 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2557 EVT ArgVT = TLI.getValueType(ArgTy);
2558 if (!ArgVT.isSimple()) return false;
2559 switch (ArgVT.getSimpleVT().SimpleTy) {
2560 default: return false;
2567 if (!Subtarget->hasSSE1())
2580 static const MCPhysReg GPR32ArgRegs[] = {
2581 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2583 static const MCPhysReg GPR64ArgRegs[] = {
2584 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2586 static const MCPhysReg XMMArgRegs[] = {
2587 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2588 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2591 unsigned GPRIdx = 0;
2592 unsigned FPRIdx = 0;
2593 for (auto const &Arg : F->args()) {
2594 MVT VT = TLI.getSimpleValueType(Arg.getType());
2595 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2597 switch (VT.SimpleTy) {
2598 default: llvm_unreachable("Unexpected value type.");
2599 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2600 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2601 case MVT::f32: // fall-through
2602 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2604 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2605 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2606 // Without this, EmitLiveInCopies may eliminate the livein if its only
2607 // use is a bitcast (which isn't turned into an instruction).
2608 unsigned ResultReg = createResultReg(RC);
2609 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2610 TII.get(TargetOpcode::COPY), ResultReg)
2611 .addReg(DstReg, getKillRegState(true));
2612 updateValueMap(&Arg, ResultReg);
2617 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2619 ImmutableCallSite *CS) {
2620 if (Subtarget->is64Bit())
2622 if (Subtarget->getTargetTriple().isOSMSVCRT())
2624 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2625 CC == CallingConv::HiPE)
2627 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2629 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2634 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2635 auto &OutVals = CLI.OutVals;
2636 auto &OutFlags = CLI.OutFlags;
2637 auto &OutRegs = CLI.OutRegs;
2638 auto &Ins = CLI.Ins;
2639 auto &InRegs = CLI.InRegs;
2640 CallingConv::ID CC = CLI.CallConv;
2641 bool &IsTailCall = CLI.IsTailCall;
2642 bool IsVarArg = CLI.IsVarArg;
2643 const Value *Callee = CLI.Callee;
2644 const char *SymName = CLI.SymName;
2646 bool Is64Bit = Subtarget->is64Bit();
2647 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2649 // Handle only C, fastcc, and webkit_js calling conventions for now.
2651 default: return false;
2652 case CallingConv::C:
2653 case CallingConv::Fast:
2654 case CallingConv::WebKit_JS:
2655 case CallingConv::X86_FastCall:
2656 case CallingConv::X86_64_Win64:
2657 case CallingConv::X86_64_SysV:
2661 // Allow SelectionDAG isel to handle tail calls.
2665 // fastcc with -tailcallopt is intended to provide a guaranteed
2666 // tail call optimization. Fastisel doesn't know how to do that.
2667 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2670 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2671 // x86-32. Special handling for x86-64 is implemented.
2672 if (IsVarArg && IsWin64)
2675 // Don't know about inalloca yet.
2676 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2679 // Fast-isel doesn't know about callee-pop yet.
2680 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2681 TM.Options.GuaranteedTailCallOpt))
2684 SmallVector<MVT, 16> OutVTs;
2685 SmallVector<unsigned, 16> ArgRegs;
2687 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2688 // instruction. This is safe because it is common to all FastISel supported
2689 // calling conventions on x86.
2690 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2691 Value *&Val = OutVals[i];
2692 ISD::ArgFlagsTy Flags = OutFlags[i];
2693 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2694 if (CI->getBitWidth() < 32) {
2696 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2698 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2702 // Passing bools around ends up doing a trunc to i1 and passing it.
2703 // Codegen this as an argument + "and 1".
2705 auto *TI = dyn_cast<TruncInst>(Val);
2707 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2708 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2710 Value *PrevVal = TI->getOperand(0);
2711 ResultReg = getRegForValue(PrevVal);
2716 if (!isTypeLegal(PrevVal->getType(), VT))
2720 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2722 if (!isTypeLegal(Val->getType(), VT))
2724 ResultReg = getRegForValue(Val);
2730 ArgRegs.push_back(ResultReg);
2731 OutVTs.push_back(VT);
2734 // Analyze operands of the call, assigning locations to each operand.
2735 SmallVector<CCValAssign, 16> ArgLocs;
2736 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2738 // Allocate shadow area for Win64
2740 CCInfo.AllocateStack(32, 8);
2742 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2744 // Get a count of how many bytes are to be pushed on the stack.
2745 unsigned NumBytes = CCInfo.getNextStackOffset();
2747 // Issue CALLSEQ_START
2748 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2749 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2750 .addImm(NumBytes).addImm(0);
2752 // Walk the register/memloc assignments, inserting copies/loads.
2753 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2754 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2755 CCValAssign const &VA = ArgLocs[i];
2756 const Value *ArgVal = OutVals[VA.getValNo()];
2757 MVT ArgVT = OutVTs[VA.getValNo()];
2759 if (ArgVT == MVT::x86mmx)
2762 unsigned ArgReg = ArgRegs[VA.getValNo()];
2764 // Promote the value if needed.
2765 switch (VA.getLocInfo()) {
2766 case CCValAssign::Full: break;
2767 case CCValAssign::SExt: {
2768 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2769 "Unexpected extend");
2770 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2772 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2773 ArgVT = VA.getLocVT();
2776 case CCValAssign::ZExt: {
2777 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2778 "Unexpected extend");
2779 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2781 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2782 ArgVT = VA.getLocVT();
2785 case CCValAssign::AExt: {
2786 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2787 "Unexpected extend");
2788 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2791 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2794 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2797 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2798 ArgVT = VA.getLocVT();
2801 case CCValAssign::BCvt: {
2802 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2803 /*TODO: Kill=*/false);
2804 assert(ArgReg && "Failed to emit a bitcast!");
2805 ArgVT = VA.getLocVT();
2808 case CCValAssign::VExt:
2809 // VExt has not been implemented, so this should be impossible to reach
2810 // for now. However, fallback to Selection DAG isel once implemented.
2812 case CCValAssign::AExtUpper:
2813 case CCValAssign::SExtUpper:
2814 case CCValAssign::ZExtUpper:
2815 case CCValAssign::FPExt:
2816 llvm_unreachable("Unexpected loc info!");
2817 case CCValAssign::Indirect:
2818 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2823 if (VA.isRegLoc()) {
2824 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2825 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2826 OutRegs.push_back(VA.getLocReg());
2828 assert(VA.isMemLoc());
2830 // Don't emit stores for undef values.
2831 if (isa<UndefValue>(ArgVal))
2834 unsigned LocMemOffset = VA.getLocMemOffset();
2836 AM.Base.Reg = RegInfo->getStackRegister();
2837 AM.Disp = LocMemOffset;
2838 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
2839 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2840 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2841 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore,
2842 ArgVT.getStoreSize(), Alignment);
2843 if (Flags.isByVal()) {
2844 X86AddressMode SrcAM;
2845 SrcAM.Base.Reg = ArgReg;
2846 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
2848 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2849 // If this is a really simple value, emit this with the Value* version
2850 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2851 // as it can cause us to reevaluate the argument.
2852 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
2855 bool ValIsKill = hasTrivialKill(ArgVal);
2856 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
2862 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2864 if (Subtarget->isPICStyleGOT()) {
2865 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2866 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2867 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2870 if (Is64Bit && IsVarArg && !IsWin64) {
2871 // From AMD64 ABI document:
2872 // For calls that may call functions that use varargs or stdargs
2873 // (prototype-less calls or calls to functions containing ellipsis (...) in
2874 // the declaration) %al is used as hidden argument to specify the number
2875 // of SSE registers used. The contents of %al do not need to match exactly
2876 // the number of registers, but must be an ubound on the number of SSE
2877 // registers used and is in the range 0 - 8 inclusive.
2879 // Count the number of XMM registers allocated.
2880 static const MCPhysReg XMMArgRegs[] = {
2881 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2882 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2884 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2885 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2886 && "SSE registers cannot be used when SSE is disabled");
2887 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2888 X86::AL).addImm(NumXMMRegs);
2891 // Materialize callee address in a register. FIXME: GV address can be
2892 // handled with a CALLpcrel32 instead.
2893 X86AddressMode CalleeAM;
2894 if (!X86SelectCallAddress(Callee, CalleeAM))
2897 unsigned CalleeOp = 0;
2898 const GlobalValue *GV = nullptr;
2899 if (CalleeAM.GV != nullptr) {
2901 } else if (CalleeAM.Base.Reg != 0) {
2902 CalleeOp = CalleeAM.Base.Reg;
2907 MachineInstrBuilder MIB;
2909 // Register-indirect call.
2910 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
2911 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2915 assert(GV && "Not a direct call");
2916 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
2918 // See if we need any target-specific flags on the GV operand.
2919 unsigned char OpFlags = 0;
2921 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2922 // external symbols most go through the PLT in PIC mode. If the symbol
2923 // has hidden or protected visibility, or if it is static or local, then
2924 // we don't need to use the PLT - we can directly call it.
2925 if (Subtarget->isTargetELF() &&
2926 TM.getRelocationModel() == Reloc::PIC_ &&
2927 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2928 OpFlags = X86II::MO_PLT;
2929 } else if (Subtarget->isPICStyleStubAny() &&
2930 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2931 (!Subtarget->getTargetTriple().isMacOSX() ||
2932 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2933 // PC-relative references to external symbols should go through $stub,
2934 // unless we're building with the leopard linker or later, which
2935 // automatically synthesizes these stubs.
2936 OpFlags = X86II::MO_DARWIN_STUB;
2939 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2941 MIB.addExternalSymbol(SymName, OpFlags);
2943 MIB.addGlobalAddress(GV, 0, OpFlags);
2946 // Add a register mask operand representing the call-preserved registers.
2947 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2948 MIB.addRegMask(TRI.getCallPreservedMask(CC));
2950 // Add an implicit use GOT pointer in EBX.
2951 if (Subtarget->isPICStyleGOT())
2952 MIB.addReg(X86::EBX, RegState::Implicit);
2954 if (Is64Bit && IsVarArg && !IsWin64)
2955 MIB.addReg(X86::AL, RegState::Implicit);
2957 // Add implicit physical register uses to the call.
2958 for (auto Reg : OutRegs)
2959 MIB.addReg(Reg, RegState::Implicit);
2961 // Issue CALLSEQ_END
2962 unsigned NumBytesForCalleeToPop =
2963 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
2964 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2965 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2966 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
2968 // Now handle call return values.
2969 SmallVector<CCValAssign, 16> RVLocs;
2970 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
2971 CLI.RetTy->getContext());
2972 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2974 // Copy all of the result registers out of their specified physreg.
2975 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
2976 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2977 CCValAssign &VA = RVLocs[i];
2978 EVT CopyVT = VA.getValVT();
2979 unsigned CopyReg = ResultReg + i;
2981 // If this is x86-64, and we disabled SSE, we can't return FP values
2982 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2983 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2984 report_fatal_error("SSE register return with SSE disabled");
2987 // If we prefer to use the value in xmm registers, copy it out as f80 and
2988 // use a truncate to move it from fp stack reg to xmm reg.
2989 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2990 isScalarFPTypeInSSEReg(VA.getValVT())) {
2992 CopyReg = createResultReg(&X86::RFP80RegClass);
2995 // Copy out the result.
2996 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2997 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
2998 InRegs.push_back(VA.getLocReg());
3000 // Round the f80 to the right size, which also moves it to the appropriate
3001 // xmm register. This is accomplished by storing the f80 value in memory
3002 // and then loading it back.
3003 if (CopyVT != VA.getValVT()) {
3004 EVT ResVT = VA.getValVT();
3005 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3006 unsigned MemSize = ResVT.getSizeInBits()/8;
3007 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3008 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3011 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3012 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3013 TII.get(Opc), ResultReg + i), FI);
3017 CLI.ResultReg = ResultReg;
3018 CLI.NumResultRegs = RVLocs.size();
3025 X86FastISel::fastSelectInstruction(const Instruction *I) {
3026 switch (I->getOpcode()) {
3028 case Instruction::Load:
3029 return X86SelectLoad(I);
3030 case Instruction::Store:
3031 return X86SelectStore(I);
3032 case Instruction::Ret:
3033 return X86SelectRet(I);
3034 case Instruction::ICmp:
3035 case Instruction::FCmp:
3036 return X86SelectCmp(I);
3037 case Instruction::ZExt:
3038 return X86SelectZExt(I);
3039 case Instruction::Br:
3040 return X86SelectBranch(I);
3041 case Instruction::LShr:
3042 case Instruction::AShr:
3043 case Instruction::Shl:
3044 return X86SelectShift(I);
3045 case Instruction::SDiv:
3046 case Instruction::UDiv:
3047 case Instruction::SRem:
3048 case Instruction::URem:
3049 return X86SelectDivRem(I);
3050 case Instruction::Select:
3051 return X86SelectSelect(I);
3052 case Instruction::Trunc:
3053 return X86SelectTrunc(I);
3054 case Instruction::FPExt:
3055 return X86SelectFPExt(I);
3056 case Instruction::FPTrunc:
3057 return X86SelectFPTrunc(I);
3058 case Instruction::IntToPtr: // Deliberate fall-through.
3059 case Instruction::PtrToInt: {
3060 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3061 EVT DstVT = TLI.getValueType(I->getType());
3062 if (DstVT.bitsGT(SrcVT))
3063 return X86SelectZExt(I);
3064 if (DstVT.bitsLT(SrcVT))
3065 return X86SelectTrunc(I);
3066 unsigned Reg = getRegForValue(I->getOperand(0));
3067 if (Reg == 0) return false;
3068 updateValueMap(I, Reg);
3076 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3080 uint64_t Imm = CI->getZExtValue();
3082 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3083 switch (VT.SimpleTy) {
3084 default: llvm_unreachable("Unexpected value type");
3087 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3090 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3095 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3096 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3097 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3098 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3105 switch (VT.SimpleTy) {
3106 default: llvm_unreachable("Unexpected value type");
3107 case MVT::i1: VT = MVT::i8; // fall-through
3108 case MVT::i8: Opc = X86::MOV8ri; break;
3109 case MVT::i16: Opc = X86::MOV16ri; break;
3110 case MVT::i32: Opc = X86::MOV32ri; break;
3112 if (isUInt<32>(Imm))
3114 else if (isInt<32>(Imm))
3115 Opc = X86::MOV64ri32;
3121 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3122 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3123 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3124 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3125 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3126 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3129 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3132 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3133 if (CFP->isNullValue())
3134 return fastMaterializeFloatZero(CFP);
3136 // Can't handle alternate code models yet.
3137 CodeModel::Model CM = TM.getCodeModel();
3138 if (CM != CodeModel::Small && CM != CodeModel::Large)
3141 // Get opcode and regclass of the output for the given load instruction.
3143 const TargetRegisterClass *RC = nullptr;
3144 switch (VT.SimpleTy) {
3147 if (X86ScalarSSEf32) {
3148 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3149 RC = &X86::FR32RegClass;
3151 Opc = X86::LD_Fp32m;
3152 RC = &X86::RFP32RegClass;
3156 if (X86ScalarSSEf64) {
3157 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3158 RC = &X86::FR64RegClass;
3160 Opc = X86::LD_Fp64m;
3161 RC = &X86::RFP64RegClass;
3165 // No f80 support yet.
3169 // MachineConstantPool wants an explicit alignment.
3170 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3172 // Alignment of vector types. FIXME!
3173 Align = DL.getTypeAllocSize(CFP->getType());
3176 // x86-32 PIC requires a PIC base register for constant pools.
3177 unsigned PICBase = 0;
3178 unsigned char OpFlag = 0;
3179 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3180 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3181 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3182 } else if (Subtarget->isPICStyleGOT()) {
3183 OpFlag = X86II::MO_GOTOFF;
3184 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3185 } else if (Subtarget->isPICStyleRIPRel() &&
3186 TM.getCodeModel() == CodeModel::Small) {
3190 // Create the load from the constant pool.
3191 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3192 unsigned ResultReg = createResultReg(RC);
3194 if (CM == CodeModel::Large) {
3195 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3196 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3198 .addConstantPoolIndex(CPI, 0, OpFlag);
3199 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3200 TII.get(Opc), ResultReg);
3201 addDirectMem(MIB, AddrReg);
3202 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3203 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
3204 TM.getDataLayout()->getPointerSize(), Align);
3205 MIB->addMemOperand(*FuncInfo.MF, MMO);
3209 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3210 TII.get(Opc), ResultReg),
3211 CPI, PICBase, OpFlag);
3215 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3216 // Can't handle alternate code models yet.
3217 if (TM.getCodeModel() != CodeModel::Small)
3220 // Materialize addresses with LEA/MOV instructions.
3222 if (X86SelectAddress(GV, AM)) {
3223 // If the expression is just a basereg, then we're done, otherwise we need
3225 if (AM.BaseType == X86AddressMode::RegBase &&
3226 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3229 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3230 if (TM.getRelocationModel() == Reloc::Static &&
3231 TLI.getPointerTy() == MVT::i64) {
3232 // The displacement code could be more than 32 bits away so we need to use
3233 // an instruction with a 64 bit immediate
3234 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3236 .addGlobalAddress(GV);
3238 unsigned Opc = TLI.getPointerTy() == MVT::i32
3239 ? (Subtarget->isTarget64BitILP32()
3240 ? X86::LEA64_32r : X86::LEA32r)
3242 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3243 TII.get(Opc), ResultReg), AM);
3250 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3251 EVT CEVT = TLI.getValueType(C->getType(), true);
3253 // Only handle simple types.
3254 if (!CEVT.isSimple())
3256 MVT VT = CEVT.getSimpleVT();
3258 if (const auto *CI = dyn_cast<ConstantInt>(C))
3259 return X86MaterializeInt(CI, VT);
3260 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3261 return X86MaterializeFP(CFP, VT);
3262 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3263 return X86MaterializeGV(GV, VT);
3268 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3269 // Fail on dynamic allocas. At this point, getRegForValue has already
3270 // checked its CSE maps, so if we're here trying to handle a dynamic
3271 // alloca, we're not going to succeed. X86SelectAddress has a
3272 // check for dynamic allocas, because it's called directly from
3273 // various places, but targetMaterializeAlloca also needs a check
3274 // in order to avoid recursion between getRegForValue,
3275 // X86SelectAddrss, and targetMaterializeAlloca.
3276 if (!FuncInfo.StaticAllocaMap.count(C))
3278 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3281 if (!X86SelectAddress(C, AM))
3283 unsigned Opc = TLI.getPointerTy() == MVT::i32
3284 ? (Subtarget->isTarget64BitILP32()
3285 ? X86::LEA64_32r : X86::LEA32r)
3287 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3288 unsigned ResultReg = createResultReg(RC);
3289 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3290 TII.get(Opc), ResultReg), AM);
3294 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3296 if (!isTypeLegal(CF->getType(), VT))
3299 // Get opcode and regclass for the given zero.
3301 const TargetRegisterClass *RC = nullptr;
3302 switch (VT.SimpleTy) {
3305 if (X86ScalarSSEf32) {
3306 Opc = X86::FsFLD0SS;
3307 RC = &X86::FR32RegClass;
3309 Opc = X86::LD_Fp032;
3310 RC = &X86::RFP32RegClass;
3314 if (X86ScalarSSEf64) {
3315 Opc = X86::FsFLD0SD;
3316 RC = &X86::FR64RegClass;
3318 Opc = X86::LD_Fp064;
3319 RC = &X86::RFP64RegClass;
3323 // No f80 support yet.
3327 unsigned ResultReg = createResultReg(RC);
3328 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3333 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3334 const LoadInst *LI) {
3335 const Value *Ptr = LI->getPointerOperand();
3337 if (!X86SelectAddress(Ptr, AM))
3340 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3342 unsigned Size = DL.getTypeAllocSize(LI->getType());
3343 unsigned Alignment = LI->getAlignment();
3345 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3346 Alignment = DL.getABITypeAlignment(LI->getType());
3348 SmallVector<MachineOperand, 8> AddrOps;
3349 AM.getFullAddress(AddrOps);
3351 MachineInstr *Result =
3352 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps,
3353 Size, Alignment, /*AllowCommute=*/true);
3357 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3358 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3359 MI->eraseFromParent();
3365 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3366 const TargetLibraryInfo *libInfo) {
3367 return new X86FastISel(funcInfo, libInfo);